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

105
Visualizações
javascript executed more than one

at the first I consider both if and else block executed. After added debugger to code, I don't know why my code run more than once.

function Submit(form) {
  var timer_starttime = document.getElementById("timer_starttime");
  var timer_finishtime = document.getElementById("timer_finishtime");
  if (wait_s.reportValidity() && wait_m.reportValidity()) {
    var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance 
    var theUrl = "/submit_program";
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        //document.getElementById("ajax_res").innerHTML = this.responseText;
        document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
        console.log(this.responseText);
        console.log("if");
        debugger;
      } else {
        document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
        console.log("else");
      }
    };
    xmlhttp.open("POST", theUrl);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send(JSON.stringify({
      "timer_finishtime": timer_finishtime.value,
      "timer_starttime": timer_starttime.value
    }));
  }
  return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
  ...
  <button type="submit" class="btn btn-primary" onclick="return Submit(this);">Save</button>

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

0

When you send an AJAX request, the request goes through a number of states. See the documentation of XMLHttpRequest.readyState for the full details.

The onreadystatechange function will be called each time the state changes. So your else block will be executed repeatedly for all the initial states. Then when the request completes successfully, the if block will be executed.

You should only check for an error in the final state 4, not treat all the other states as errors.

function Submit(form) {
  var timer_starttime = document.getElementById("timer_starttime");
  var timer_finishtime = document.getElementById("timer_finishtime");
  if (wait_s.reportValidity() && wait_m.reportValidity()) {
    var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance 
    var theUrl = "/submit_program";
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4) {
        if (this.status == 200) {
          //document.getElementById("ajax_res").innerHTML = this.responseText;
          document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
          console.log(this.responseText);
          console.log("if");
          debugger;
        } else {
          document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
          console.log("else");
        }
      }
    };
    xmlhttp.open("POST", theUrl);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send(JSON.stringify({
      "timer_finishtime": timer_finishtime.value,
      "timer_starttime": timer_starttime.value
    }));
  }
  return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
  ...
  <button type="submit" class="btn btn-primary" onclick="return Submit(this);">Save</button>

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