I am using Ajax for inserting data into MySQL with PHP, see my code below:
var c = 0;//initialize counter
function add(){
for (var i = 0; i < 10; i++) {
$.ajax({
type: "POST",
url: "insert.php",
data: {
id: id,
name: name,
email: email,
},
dataType: "json",
success: function (res) {
c++;//increment counter
},
});
}
alert(c);//display counter
}
what I want to do is show the alert (number of times the insert operation is done) after the for loop ends. I have did it like above code it does not work. it always shows zero.
Is there any way to done the same functionality?
2
Answers
this way works.
You need to use promisse with the use of async and wait. You use async and create the add method as async
After that, you add await in $.ajax because only in this way ajax will only increment c++ only after the POST returns, this has to be done because you start several POST within the for, and so have to wait for the completion of each to be able to increment correctly.
In conclusion, you can finally get the value of variable c
Don’t forget, the method call has to be made within document.ready
Consider the following.
When you perform the last loop,
i
will be 9 and then incremented to 10. So we can check ifi
is equal to10
, and then we know the loop has ran the last time.