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

216
Vistas
javascript url call executing twice

I am trying to show this json data in a javascript alert box, but it shows it twice (same content). It is working, but I do not know why it is displaying two alerts. (javascript is not my preferred language).

This is the response from the URL called:

{
  "type": "error",
  "response": {
    "message": "Could not start app"
  }
}

This is the code I am using:

<script type="text/javascript">
       
        function call() {
            const Http = new XMLHttpRequest();
            const url='https://url_to_get_the_response';
            Http.open("GET", url);
            Http.send();
            Http.onreadystatechange = (e) => {
                if (Http.responseText) {
                alert(Http.responseText);
               }
           }
    }
    </script>

And I get two alerts, both containing the same thing (the .json result). I only want one of them.

I have tried adding a return; and break call; in the if (Http.responseText) section. Adding the return; in the if statement didn't do anything and adding the break call; stopped it working.

Any advice on this? Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You approach is correct. onreadystatechange event is triggered multiple times, as the readyState attribute changes from the beginning to the end of an API call.

On adding if condition for the appropriate readyState and status value that comes in the XMLHttpRequest Object. Solves this issue.

You can read more about those attributes here readyState, status

function call() {
        const Http = new XMLHttpRequest();
        const url='https://jsonplaceholder.typicode.com/todos/1';
        Http.open("GET", url);
        Http.send();
        Http.onreadystatechange = (e) => {
            if (Http.readyState == 4 && Http.status == 200 && Http.responseText) {
            alert(Http.responseText);
           }
       }
  }
<button onclick='call()'>Call</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