Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
increment a counter after each ajax insert then show it as a message

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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

$(() => {
})
about 4 years ago · Juan Pablo Isaza Relatório

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda