Ajax php call and setInterval() not running together - setinterval

Basically my code contains two modules. One to update the data in an ajax call and another module loads the response from an external php to a element. I am trying to implement a chat mechanism. Where user texts data and gets updated chat history without loading the page
The submit ajaxsubmit.php wont work properly with the load fetch-conversation.php loading chat data. This results in execution of alert("Please Fill All Fields")
function auto_refresh()
{
if(writing==false){$('#message-container').load(<?php echo "'fetch-conversation.php?id=$id'"?>);}
}
setInterval('auto_refresh()', 1000);
<script>
var writing=false;
$(document).ready(function(){
$("#submit").click(function(){
writing=true;
var content = $("#content").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'content='+ content ;
if(content=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
writing=false;
}
});
}
return false;
});
});
</script>

Related

Error: Can't set headers after they are sent - Ajax, Node, Express

I'm trying to using Airtable, node.js, express.js and jquery to create a simple user authentication functionality but I'm fairly new at this and I'm running into a problem I can't seem to fix and the articles I've read I can't seem to grasp or adapt to my particular situation.
I have this Ajax call in my html doc:
$("#checkUser").submit(function(e) {
var studentID = $('input[name="student"]').val()
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
$(window).attr("location", window.location.href + 'Dashboard?student=' + studentID);
},
error: function(data){
console.log("User not found. Try again");
}
});
});
This call sends the inputted username and data to the server which then processes it in the following way:
app.post('/checkUser', urlencodedParser, function(request,response){
var user = JSON.stringify(request.body);
user = JSON.parse(user);
base('RegisteredStudents').select({
filterByFormula: '{UserID} = ' + user.student,
view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
response.sendStatus(200);
});
fetchNextPage();
}, function done(error) {
response.sendStatus(404);
});
});
If the user exists in the database of Airtable, it should send '200' which the Ajax then reacts by redirecting accordingly to the user's profile. Otherwise, if the user does not exist, the server should respond with '404', which the Ajax call should react to by printing a statement in the console. While it does do these two things well, the server breaks down when, after a student puts in the wrong user ID and the Ajax prints the statement, the student tries to put once more a userID. I get the " Can't set headers after they are sent. " message. Please, how can I solve this?
Thank you!
You have two response.send..., you can only send data once. Either make sure only one runs with some conditional or add return before all response.send... so if any of them runs, the program will return and the other response.send.. will not run.

Saving data to database without using a form tag

I am very new to web programming. I took an online course covering html, css, js and node, now I started to build an online calendar application. In my calendar page each day of the year is represented by a text input. So there are 365 inputs in the page. What I am trying to do is; when an input lost focus, the value of the input must be stored in a mongo database. I assume that I should send a post request to my index.js file from the calendar.ejs file when the input lost focus. But all the examples I could find so far use form tag. Is it possible to send a post request when the onfocusout event of a text input is triggered?
Have you tried jQuery $.ajax?
http://api.jquery.com/jquery.ajax/
var request = $.ajax({
url: "http://www.your-url.com",
type: "POST",
data: { ... } // payload to the api
}).done(function (response, textStatus, jqXHR) {
//your code
}).fail(function (jqXHR, textStatus, errorThrown) {
console.error(
"The following error occurred: " +
textStatus, errorThrown
);
}).always(function () {
// your code
});

Node, Express, Ajax, Form Submission

Help, I'm Stuck! I am playing with a CRUD setup with Node Express but with AJAX post request. I have the read form working fine.
The form has one input filed which is a lookup email. AJAX post the form data with the following code
if ($("#rsvp-search-form").length) {
$("#rsvp-search-form").validate({
rules: {
...
},
messages: {
...
},
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/",
data: $(form).serialize(),
success: function (data, textStatus, jqXHR){
if (typeof data.redirect == 'string')
window.location = data.redirect;
}
,
error: function() {
$( "#loader").hide();
$( "#error").slideDown( "slow" );
setTimeout(function() {
$( "#error").slideUp( "slow" );
}, 5000);
}
});
return false; // required to block normal submit since you used ajax
}
});
}
I have a express post route to '/' that returns a status with res.status(#).send() and the proper success/error block is executed based on the whether status # is 400 or 200.
Now on the update form I have the same basic setup with many more form inputs, but the AJAX code does not process the res.status(#).send() response by executing the proper success or error block, instead it is just loading a new page with the same url as the request was processed from.
The AJAX code request is similar to the top with difference of url:
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
//The website when loaded has an invitation
//object that is passed by express
url: "/rsvp/" +invitation._id,
data: $(form).serialize(),
dataType: 'application/json'
I verified that the proper post route is running and receiving the invitation._id. It returns res.staus(#).send() but the ajax does not process the success or error block it just redirects to the requesting url but does not actually render the url.
I don't know if it is just that the form is still processing the default action, if the response from express is not correct, etc etc
I hope I have been clear on my issue and someone knows what I am doing wrong here.
Regards!
Update!
I got it working. Though the url with variable was correct and express was receiving the proper id, JS was throwing an error causing everything to crash. I never caught the error because the page would reload to the blank page and clear the console. I fixed it by saving the id in a hidden field when rendering the form and used that instead. Seems to have fixed the problem.
Thanks for looking!

Send variable from mongoose query to page without reload on click

I have a link on my site. When clicked it'll call a function that does a mongoose query.
I'd like the results of that query to be sent to the same page in a variable without reloading the page. How do I do that? Right now it is just rendering the page again with new query result data.
// List comments for specified chapter id.
commentController.list = function (req, res) {
var chapterId = req.params.chapterId;
var query = { chapterId: chapterId };
Chapter.find({ _id: chapterId }).then(function (chapter) {
var chapter = chapter;
Comment.find(query).then(function (data) {
console.log(chapter);
Chapter.find().then(function(chapters){
return res.render({'chapterlinks', commentList: data, user: req.user, chapterq: chapter, chapters:chapters });
})
});
})
};
You just need to make that request from your browser via AJAX:
https://www.w3schools.com/xml/ajax_intro.asp
This would be in the code for your client (browser), not the code for your server (nodejs).
UPDATE:
Here's a simple example, which uses jQuery to make things easier:
(1) create a function that performs and handles the ajax request
function getChapterLinks(chapterId) {
$.ajax({
url: "/chapterLinks/"+chapterId,
}).done(function(data) {
//here you should do something with data
console.log(data);
});
}
(2) bind that function to a DOM element's click event
$( "a#chapterLinks1" ).click(function() {
getChapterLinks(1);
});
(3) make sure that DOM element is somewhere in you html
<a id="chapterLinks1">Get ChapterLinks 1</a>
Now when this a#chapterLinks1 element is clicked, it will use AJAX to fetch the response of /chaptersLink/1 from your server without reloading the page.
references:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.click/

Ajax call working on localhost but does not on azure-webites.net

<script type="text/javascript">
$(document).ready(function () {
function validemail(isemail) {
var emailReg = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return emailReg.test(isemail);
}
$("#<%=txtEmail.ClientID %>").blur(function () {
if ($("#<%=txtEmail.ClientID %>").siblings().size() > 0) {
$("div").remove(".tooltips");
}
});
$("#btnSubmit").click(function () {
var name = $("#<%=txtName.ClientID %>").val();
var email = $("#<%=txtEmail.ClientID %>").val();
var message = $("#<%=txtMessage.ClientID %>").val();
if (name != '' && email != '' && message != '') {
if (validemail(email)) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://abcname.azurewebsites.net/Contact.aspx/InsertData",
data: "{'customername':'" + name + "','customeremail':'" + email + "','customermessage':'" + message + "'}",
dataType: "json",
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$("#<%=txtName.ClientID %>").val('');
$("#<%=txtEmail.ClientID %>").val('');
$("#<%=txtMessage.ClientID %>").val('');
alert('Details submitted successfully');
}
},
error: function (result) {
alert("An error occur while submitting details.");
}
});
}
else {
$("#<%=txtEmail.ClientID %>").focus();
$("<div class='tooltips'><span>Invalid Email Address</span></div>").insertAfter("#<%=txtEmail.ClientID %>");
}
}
else {
alert('Please fill all the fields');
}
});
});
</script>
Above code perfectly working on local host but it doesn't on server side. If there would any error on the .cs file then it will show alert box, but it even doesn't showing alert box that "An error occur while submitting details"
url: "http://abcname.azurewebsites.net/Contact.aspx/InsertData",
Based on the URL, I suspected that you were using WebMethod to handle AJAX request in WebForms application. Since there were .aspx suffix in your URL, please make sure you have commented out the following code which default exist in RouteConfig.cs.
//settings.AutoRedirectMode = RedirectMode.Permanent;
but it even doesn't showing alert box that "An error occur while submitting details"
var obj = data.d;
The reason for this may be that the response is came back but it doesn’t contain a property named d or its value doesn’t equals ‘true’. I suggest use a tool to view the detail response message. Fiddler is common tool which could help you do it.
In addition, did you send the AJAX request from different domain as 'http://abcname.azurewebsites.net'? For example, the code which you posted is in the website named 'http://defname.azurewebsites.net'. If it is true, you need to configure CORS in abcname web app. Steps below are for your reference.
In Azure portal, open web app abcname.
On menus bar, click CORS.
Input the domain name in the ‘Allowed Regions’ textboxes.
Click [Save] button to save all your operations.

Resources