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
Call fun2 in success of func1
function func1(){
$.ajax({
url:'',
success:function(){
func2();
}
})
You can set the option "async" to false (for the first ajax call).
This means that function 2 will be called after function 1 has received a response, i.e. finished it's execution.
function func1(){
$.ajax({
url:'',
async: false
});
});
you could also pass your function as a parameter like this:
var secondFunc = function (func) {
//Do ajax req or smt
func("answer", "params");
};
var firstFunc = function() {
secondFunc(
function (answerFromFunc2, paramsFromfunc2) {
var a = answerFromFunc2;
var b = paramsFromfunc2;
}
);
//Do smt after the function request to the server is done
var doSmt = "another func or variable";
};
firstFunc();
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.
Move func2 inside func1->ajax->succes callback
$("#updateLocation").click(function(e) {
e.preventdefault;
func1();
//func2();
});
return false;
});
function func1() {
$.ajax({
url: '',
success: function() { /* other stuff */
func2();
}
});
});
function func2() {
$.ajax({
url: '',
});
});
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});
}