JS returns before AJAX causes output to return?

Possible duplicate:
How to return AJAX response text?

I call the javascript method, which in turn sends an Ajax request and gives a response. I get the result in a callback method like success.
Here Ajax returns some result, on average, when the javascript method returns the result (something like undefined).
But it should return only ajax result.
The problem I have been identified, Javascript and Ajax are both running.
How to stop them and execute Ajax first, and the result should send a function that returns the result.
Any idea is much appreciated .. :)

+4
source share
1 answer

By default, $.ajax (and anything that uses it, such as $.post ), performs asynchronous requests. You can make the request synchronous by specifying async:false (see documentation ). However, I do not recommend using synchronous AJAX requests, as this reduces performance and leads to poor user experience. Instead, consider using a callback that is called in your success handler when the result is complete.

Here are two arbitrary and simple examples where we have an anchor that we want the text to be replaced with the result of the AJAX call when clicked. Both do the same, but the second is preferable 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. }); 
+7
source

Source: https://habr.com/ru/post/1441453/


All Articles