tags:

views:

66

answers:

3

In the following jquery function, can someone explain to me why "second" is being executed before "first"? I assume that the entire $.post request should be completed before the browser moves on to the next line of code, but that does not appear to be happening.

function getGUID () {
$.post(getGUIDScript, function(data, textStatus) { 
 alert("first");
 GUID = data;
 }, 
 'text');

 alert("second");  
}

Thanks for the responses below guys. For posterities sake, the code above can be written as is shown below to wait until the post is completed before moving on.

function getGUID () {
$.ajax({
type: "POST",
url: getGUIDScript,
async: false,
success: function(data) {
 alert("first");
 GUID = data;
}
});
    alert("second");
}

This will set off the first alert and then the second.

+3  A: 

The post is done asynchronously so the following statement is executed before the first one completes. If you need them to be synchronous, you need to use $.ajax and set the async parameter to false. Better yet, use the callback mechanism for post to wait and perform the subsequent actions after the ajax call performed by the post is completed.

tvanfosson
Any way to have it wait until it is completed? I'm returning from the function before the $.post is completed.
Michael Shnitzer
The only way I can think of is to include the rest of the executing script as a callback to the POST.
Steven Xu
See my update. The best way would be to pass in a function to your function to execute as a callback on the post.
tvanfosson
+3  A: 

$.post() initializes an asynchronous POST request that takes a callback as an argument. The callback executes when the server returns a response to the POST request.

Steven Xu
+2  A: 

If you'd like to make a synchronous ajax call, you can set asyc to false. See http://docs.jquery.com/Ajax/jQuery.ajax#options

Andy Gaskell