Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS returning before AJAX call returning output? [duplicate]

Possible Duplicate:
How to return AJAX response Text?

I'm calling a javascript method which in turn sends Ajax request and gives response.I'm getting the result in callback method like "success".
Here Ajax is returning some result, in the mean while javascript method returning result (something as undefined).
But it should return ajax result only.
The problem i was identified is, Javascript and Ajax are both concurrently executing.
How to stop them and first execut Ajax and it's result must send to function which returns the result.
Any idea is Highly Appreciated.. :)

like image 979
Mr.Chowdary Avatar asked Feb 18 '23 18:02

Mr.Chowdary


1 Answers

By default, $.ajax (and anything that uses it, such as $.post) makes asynchronous requests. You can make the request synchronous by specifying async:false (see documentation). I don't recommend you use synchronous AJAX requests, though, as it degrades performance and leads to poor user experience. Instead, consider using a callback which is invoked in your success handler when the result is complete.

Here are two arbitrary and simple examples, where we have an anchor that we want to have the text replaced from the result of an AJAX call when clicked. Both do the same thing, but the second one is preferred because it keeps the browser responsive.

Synchronous:

function invokeAjaxSync() {
   var text;

   $.ajax({url: '/path/to/resource', async:false, success: function(result) {
      text = result.toString();
   }}); // will wait until this call is complete

   return text;
}

$('a.example').click(function() {
    $(this).text(invokeAjaxSync()); // works, but the browser will be unresponsive while waiting for a response.
});

Asynchronous (better):

function invokeAjaxAsync(callback) { 
   $.ajax({url:'/path/to/resource', success: function(result) {
         callback(result);
   }});
}


$('a.example').click(function() {
     var $this = $(this);

     invokeAjaxAsync(function(result) {
        $this.text(result.toString());
     }); // browser will remain responsive, but still update text when the AJAX call completes.
});
like image 102
moribvndvs Avatar answered Mar 04 '23 20:03

moribvndvs