I’m trying to keep from cutting and pasting code so I made a wrapper for saving data to a webserver:
function saveData(newData) {
//clear our error message out.
$("#Status").html("");
var anID;
//save the data to the server
$.ajax({
type: "POST",
url: "/John/SaveSomeData",
data: JSON.stringify(newData),
async: false,
contentType: 'application/json; charset=utf-8',
datatype: "json",
traditional: false,
success: function (sReturn) {
anID = parseInt(sReturn);
if (isNaN(anID)) {
$("#Status").html("Error: " + sReturn);
return -1;
}
}
}); //end AJAX call
return anID;
} //end save data
Basically, the function above returns a positive integer if it worked and -1 if it got an error from the server. The webserver returns an integer value if the data was sucessfully added or some text if an error occurs.
The data being sent and returned is measured in bytes… with the absolute worst case being 200 bytes (yes, bytes, not kilo, mega, or giga… just bytes) So I have no concern with the posibility of lots of data being sent and the time to process it.
I use the above code as follows(one in an add button another in a save button):
$("#addButton").click(function (event) {
//validate data locally
//cut some unimportant code
var newData = /*newdata junk cut*/
var myID = saveData(newData);
if (myID != -1) {
//cut code for adding result to a list
//snip the rest of the code
The obvious problem I am having is jquery fires the ajax call and continues on not waiting for the ajax call to finish. Basically, the server could return “failed to add” and “add button event” would continue to process like it was sucessful.
The data being sent to the webserver is good, processes correctly, AND the response is correct from the webserver. This is purely an issue with sync/async issue and not the data to/from server.
My understanding is the “async: false,” line should force jquery to wait for the ajax call to finish before doing anything else.
The coding for what happens on add versus save are different thus I didn’t want the code in with the Ajax.
Do I need to convert the ajax portion to something more like:
var ajaxReturn = $.ajax({
type: "POST",
url: remote_url,
async: false, }).responseText;
ajaxReturn.done(function(msg) {
$("#log").html( msg );
});
ajaxReturn.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Not sure if this is what makes you think it isn’t synchronous, but your function will never return
-1because you put thatreturnstatement in thesuccess:callback. Instead it should assign-1toanID.