0

I'm using an ajax request inside im.js so it will call my PHP server from the js and get the feedback. However, I need to update an variable based on the callback of the .ajax function like this:

var picture = "<img src='https://www.123.com/pictures/unknown.jpg' width='30' />";
$.ajax({'type':'GET', 'async':false,'url':'https://www.123.com/site/getpic?username=' + username,
'success':function(callback){
picture = "<img src='" + callback + "' width='30' />";
} //ajax success
});  //ajax

See that if i delete "async: false", the variable picture will not be updated since ajax is async, and if I disable it like this, it blocks the whole page from going on even I load the whole im.js async.

Please help: How can I update the variable, in the meantime, do not block the page?

Thanks

jackhao
  • 3,457
  • 3
  • 22
  • 43

1 Answers1

0

You can still set the variable from within the async success handler callback, but any code that needs that variable's value immediately must also be in callback or called from the callback. That's how you handle asynchronous responses.

var picture = "<img src='https://www.123.com/pictures/unknown.jpg' width='30' />";

$.ajax({type:'GET', 
        async:true,
        url:'https://www.123.com/site/getpic?username=' + username,
        success:function(response){
            picture = "<img src='" + response + "' width='30' />";
            // code that uses this picture value immediately must be located here
            // or called from here
        }
});
// code that uses the new value of the picture variable cannot be here
// because the variable's new value is not set yet
// because the ajax call has not yet completed and thus has not called its
// success handler yet
jfriend00
  • 683,504
  • 96
  • 985
  • 979