I have a question as to how client-side code is processed along with server-side responses.
I have some code (too complex and long to post here) that when it runs, calls a function which runs some server-side code using a HTTPRequest Object, and returns a string to the page that the function was called from. For some reason, I think that the client-side code is being processed, the string is returned (too late) and my code is failing because of it. For example, I call my function with the HTTPRequest, next line I try to display the returned value (the string from the HTTPRequest) in an alert, and the alert shows up as blank. A few lines later in the code though, the same alert shows up with the value returned. So, basically, I am under the impression that the first client-side alert is being processed so that it displays a string which has not yet been returned, whereas the second alert was processed later, (ergo. giving the server time to process the request) and displaying the requested string. Does this theory sound logical? Will client-side code run, regardless of whether or not a HTTPRequest was completed? If so, are there any ways to prevent the client-side code from executing until a response is received from the server?
-
possible duplicate of Asynchronous/Synchronous Javascriptuser123444555621– user1234445556212012-05-10 17:51:04 +00:00Commented May 10, 2012 at 17:51
-
Yes, by defaults it's async and it will continue to run your code.Zachary– Zachary2012-05-10 17:52:31 +00:00Commented May 10, 2012 at 17:52
-
Whatever you do not make the request async = false, JS is single threaded and this will lock up your entire site!!!marteljn– marteljn2012-05-10 17:56:16 +00:00Commented May 10, 2012 at 17:56
Add a comment
|
3 Answers
You need to bind an anonymous function to the onreadystatechange event of the XmlHttpRequest object so:
//xhr is an instance of the XmlHTTPRequest object that you have opened correctly
xhr.onreadystatechange = function(){ //4 means the request was successful
if (xhr.readyState === 4){
//Your code here
}
}
Comments
You need to make sure that your bit of code that attempts to display / act on the returned value is within the scope of the ajax routine. That's the only way to guarantee that the response will not be acted upon until the request has been completed (whether successfully or not). For example, if you are using jQuery: CORRECT
jQuery.get('ajax/ajax.getSomeData.php',{id:id}, function(data) {
$('#myDIV').html(data);
});
INCORRECT
jQuery.get('ajax/ajax.getSomeData.php',{id:id}, function(data) {});
$('#myDIV').html(data);