Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make jQuery wait for an Ajax call to finish before it returns?

Tags:

jquery

ajax

I have a server side function that requires login. If the user is logged in the function will return 1 on success. If not, the function will return the login-page.

I want to call the function using Ajax and jQuery. What I do is submit the request with an ordinary link, with a click-function applied on it. If the user is not logged in or the function fails, I want the Ajax-call to return true, so that the href triggers.

However, when I use the following code, the function exits before the Ajax call is done.

How can I redirect the user gracefully to the loginpage?

$(".my_link").click(     function(){     $.ajax({         url: $(this).attr('href'),         type: 'GET',         cache: false,         timeout: 30000,         error: function(){             return true;         },         success: function(msg){              if (parseFloat(msg)){                 return false;             } else {                 return true;             }         }     }); }); 
like image 679
Hobhouse Avatar asked Apr 16 '09 12:04

Hobhouse


People also ask

Is there a way to limit the time an AJAX call will run?

Not possible. It's the browser's responsibility.

How do you check if AJAX call is completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How do you send AJAX request every 5 seconds?

Use just setTimeout(executeQuery, 5000); instead of setTimeout('executeQuery()', 5000); - it's shorter and faster.


2 Answers

If you don't want the $.ajax() function to return immediately, set the async option to false:

$(".my_link").click(     function(){     $.ajax({         url: $(this).attr('href'),         type: 'GET',         async: false,         cache: false,         timeout: 30000,         fail: function(){             return true;         },         done: function(msg){              if (parseFloat(msg)){                 return false;             } else {                 return true;             }         }     }); }); 

But, I would note that this would be counter to the point of AJAX. Also, you should be handling the response in the fail and done functions. Those functions will only be called when the response is received from the server.

like image 104
cgp Avatar answered Oct 07 '22 15:10

cgp


I am not using $.ajax but the $.post and $.get functions, so if I need to wait for the response, I use this:

$.ajaxSetup({async: false}); $.get("..."); 
like image 34
MilMike Avatar answered Oct 07 '22 13:10

MilMike