I am calling two function on change event.
function1();
function2();
function1()
: is a ajax call
function2()
: is getting executed before function1().
Why is this happening?
Any help?
I am calling two function on change event.
function1();
function2();
function1()
: is a ajax call
function2()
: is getting executed before function1().
Why is this happening?
Any help?
The first A of Ajax
means asynchronous
, i.e. the regular Javascript program flow will continue while the Ajax request is still being processed. Therefore, function2
will be executed before the Ajax request initiated from function1
will be finished.
Solution: Every asynchronous method in Javascript will provide you with a so-called callback
, which is a function that will be called after the asynchronous method finished. In jQuery.ajax()
this callback is provided with the parameter success
. If you put the call to function2
inside this callback, it will work.
function1() {
...
$.ajax({
url: '...',
type: 'GET',
success: function(data) {
// this will be executed after the asynchronous method finishes
function2();
}
});
}
Please look at the code written below:
function1() {
$.ajax({
url: myurl,
type: 'GET',
async:false,
success: function(response) {
function2();
}
});
}
Please note here the "async:false" will ensure that the success method will call when the first function has been successfully executed. So you should use "async:false" to ensure that the function2() will call after function1().
if function1()
is ajax function then call function2()
on the success of your ajax
if you are using jquery ajax
function1() {
$.ajax({
url: myurl,
type: 'GET',
success: function(response) {
function2();
}
});
}
Call your function2 after successful response from Ajax.
function function1()
{
//Ajax Call
..
..
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
function2();
}
}
Normally Call like this
function1(function() {
function2();
});
If it is Ajax call like this
function function1() {
$.ajax({
url: "url",
type: 'POST',
}).success(function (html) {
function2();
});
}
jQuery ajax returns deferred object (http://api.jquery.com/category/deferred-object/), its really usefull for things like yours. By the way, deferred object support chaining pattern, so you can call more than one function.
So, to run one function after another you can do next
function ajaxCall(){
return $.get('your/api/call', {param:1});
}
function fun1(){
console.log('Function 1 was called');
}
function fun2(){
console.log('Function 2 was called');
}
ajaxCall().done(fun1).done(fun2);
Or you can use $.when
$.when( $.get('your/api/call') )
.then(function(){ alert(1); })
.then(function(){ alert(2); });
Usefull links: