skip to Main Content

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


  1. 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

    $(() => {
    })
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search