I have 2 ajax call in 2 difference functions. I want to use .click to call these 2 functions . The func1 is inserting data in to database, then func2 is to retrieve the data so my question is how to wait until the func1 fully complete then it only execute the func2.
I tried .delay(), it works but i think this is a stupid solution.
$("#updateLocation").click(function(e){
e.preventdefault;
func1();
func2();
});
return false;
});
function func1(){
$.ajax({
url:'',
});
});
function func2(){
$.ajax({
url:'',
});
});
If you don't want the $. ajax() function to return immediately, set the async option to false : $(". my_link").
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
jQuery ajaxStop() Method 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.
Three ways:
Call func2 on success of func1:
function func1() {
$.ajax({ ... }).done(func2);
}
Use Deferred
API to call func2 when funky completes:
e.preventDefault();
$.when(func1).then(func2);
Make func1 synchronous (not recommended):
function func1() {
$.ajax({url: '', async: false});
}
Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately.
JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
},
error :function(jqXHR, textStatus, errorThrown)
{
alert("something went wrong");
}
});
You will want to call your second AJAX function from the success handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With