Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda