[ACCEPTED]-jQuery Ajax call - Set variable value on success-web-services

Accepted answer
Score: 38

Since you need this behavior in the unload 7 event, you will have to make a synchronous 6 call instead. However it may freeze the 5 browser window/tab dependent on how long 4 the call will take, but because you're effectively 3 trying to prevent the user from closing 2 the window...

Add async: false to your JSON to make a 1 synchronous call.

Score: 8

An example of jquery page:

var html = $.ajax({
  url: "some.php",
  async: false

Source: http://api.jquery.com/jQuery.ajax/


Score: 4

The thing is that the request to Ajax call 6 is asynchronous. So by the time you are 5 checking you IsInitialized the call has 4 not finished yet.

I suggest specifying your 3 behaviour in the success function.

Basically 2 having synchronous calls with ajax is if 1 not impossible than really discouraged.

Score: 2

You could theoretically kill the event (return 13 false) and close the window on success, but 12 I think you would run into Javascript restrictions 11 set by some users, and also just confuse 10 them as to why their window isn't closing. So, I 9 agree with Pawel Krakowiak, the ajax call 8 itself must be synchronous.

I'll add that 7 you'll want to give the user some notification 6 that you are checking on status (not a popup, please. one 5 of those nice notification banners at the 4 top of the window) and be sure to set the 3 $.ajax "timeout" option to something more 2 reasonable for this situation, so they aren't 1 waiting forever for the window to close.

Score: 2

I had a similar problem with attempting 12 to set a property for a data object through 11 the success callback of an ajax request. Using 10 async: false didn't solve my issue, either. What I ended 9 up doing was to use a setTimeout call outside the 8 ajax call, and set the timeout value to 7 1, like so:

function getSessionid() {  
        type: 'POST',  
        url: 'getSession.php',  
        dataType: 'text',  
        success: function(result){myData.sessionid = result;},   
        error: function(data) {alert("Error!\n" + data);} 
    setTimeout(function() {alert('sessionid = ' + myData.sessionid);},1);  

Just having that 1 millisecond 6 delay made all the difference in the world. Without 5 it, the sessionid property wouldn't set outside the 4 ajax call, though alerts within the callback 3 showed that it was, indeed, being set. It's 2 something to think about, should you come 1 up against a similar problem.

Score: 1

Looks like the best approach for me was 9 to use the async: false option on my ajax 8 call. Although I understand Rashack's hesitation 7 for doing this, I think that this situation 6 justifies the means.

Also great point by 5 Jerph about making sure that I don't leave 4 the user hanging while I am trying to verify 3 their status. That coupled w/ the timeout 2 option is important.

Thanks to everyone who 1 commented.

More Related questions