0

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?

  • To show the value you'd need to put `alert(c)` inside the `success` handler function. However there's some major problems with this code. Firstly, `alert()` will block JS from continuing before the notification is dismissed. I'd strongly suggest you use `console.log(c)` instead. Secondly, flooding your server with 10 requests is a really bad idea. What is your actual goal - as this code seems redundant. – Rory McCrossan Dec 05 '21 at 16:18
  • I use alert just for testing purpose. What is your alternative way for doing that? I am using that inside student mark sheet, I want to insert each record to a database. – for main Dec 05 '21 at 16:23
  • Send one request to your server containing the details of all 10 students, then loop through the data on the server side – Rory McCrossan Dec 05 '21 at 16:26
  • Another issue with the current code is that Ajax is asynchronous (non-blocking) so the alert will be executed immediately, before the first responses has even come back to the client. – M. Eriksson Dec 05 '21 at 16:26
  • @Rory McCrossan, Could you please provide a code example as an answer? for what you suggested? – for main Dec 05 '21 at 16:33
  • Relevant: [how to return the value from an async call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323) – freedomn-m Dec 05 '21 at 17:27
  • Given the async nature of ajax, I would recommend you 1 do NOT loop over the ajax this way. and 2. When you start the ajax, increment a record count (say in a hidden field with id=xcount) and on ajax success make a call to the function add() ONCE AGAIN until the record count reaches TEN ; 3. if record count reaches TEN, trigger the alert – Ken Lee Dec 05 '21 at 17:54
  • Your alert is fired before any of your ajax calls return, so it should display 0. But that aside, I would still advise **don't do this**. Looping over ajax calls is almost never the answer. 1) it's inefficient and a waste of bandwidth 2) since ajax is asynchronous, the 10th item could return before the 1st, so you would have to make an interval to poll what has returned so far. Instead, since you're sending the data as JSON anyway, build a single array of all of the contacts you want to update, send it all in one call, handle everything server side, and then echo back the number of successes. – PoorlyWrittenCode Dec 05 '21 at 20:33

2 Answers2

0

this way works.

var c = 0;
async function add() {
    for (var i = 0; i < 10; i++) {
        await $.ajax({
            type: "POST",
            url: "https://upwork.codefusiontm.com/stack/002",
            data: {
                id: "id",
                name: "name",
                email: "email",
            },
            dataType: "json",
            success: function (res) {
                c++;//increment counter
            },
        });
    }
}

$(() => {
    add().then(() => {
        console.log("=>",c)
    })
})

You need to use promisse with the use of async and wait. You use async and create the add method as async

async function add() {

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.

await $.ajax({

In conclusion, you can finally get the value of variable c

$(() => {
    add().then(() => {
        console.log("=>",c)
    })
})

Don't forget, the method call has to be made within document.ready

$(() => {
})
0

Consider the following.

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++;
        if (i == 10) {
          alert(c); //display counter
        }
      },
    });
  }
}

When you perform the last loop, i will be 9 and then incremented to 10. So we can check if i is equal to 10, and then we know the loop has ran the last time.

Twisty
  • 30,304
  • 2
  • 26
  • 45