I’m not sure this is the best way to send 2 ajax togheter for facebook api.
But it works, the problem is that sometimes i get the second ajax (result_flow.php) before the first (result.php)
Will be helpful delay second ajax (url:result_flow.php) for 3 seconds or change this code in someway to give a order.
I tried setTimeout but didn’t work.
$('#sub').click(function () {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data='+ data + '&total=' + total + '&subscriber_id=' + subscriber_id+ '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if(data==='success'){
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
}
}
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
setTimeout(function(){
console.log(data);
if(data==='success'){
}
},3000);
}
});
}
3
Answers
First,
setTimeout()
is not working because you put it inside the callback, which means it will be executed when the request is already done. Anyway that’s not a proper way to handle such a task, you should put the second request inside the first’s callback, so that it will be executed as the first one finishes.The code looks like this:
Note that in my code the second request is sent just if the first one is successful because it’s placed within the
if (data === 'success') {...}
statement.You should call them in chain. Success… then… using promise is the best way.
Never trust the order you receive if is not explicitly written by you.
JQuery Ajax
You can do something like this:
I would suggest to use async/await nowadays, it is quite easy to use AJAX calls sequencially:
Not tested, as i donĀ“t work with jQuery – but it should give you the idea. Since
$.ajax/$.post
supports Promises, it should work with async/await. Be aware that you may need to transpile your code with Babel for older browsers, but i suggest using Babel anyway.If you want to use both AJAX calls in parallel, use Promise.all (because they do not depend on each other) – the results will be in order, so you can make sure the callback code is called in order.