Uncaught Domexception: Failed to execute 'send' on 'Xmlhttprequest': The Object’s state must be OPENED

Asked

Viewed 1,584 times

1

I’ve been needing to make a synchronous request and the result has given me this error.

Uncaught Domexception: Failed to execute 'send' on 'Xmlhttprequest': The Object’s state must be OPENED.

The idea of this code is to make it run one call after another

function requisicaoSincrona(categoria, callback){
     xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    values = {"modulo":modulo,"categoria":categoria};
    myJsonString = JSON.stringify(values);
    xmlhttp.onreadystatechange = respond;

    xmlhttp.open("POST", "classes/getData.php", true);
    xmlhttp.send(myJsonString);
    //xmlhttp.abort();
    //como o código executado na volta da requisição é a função respond, chamamos o callback aqui
    function respond() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            x = document.getElementsByClassName('terceiraEtapa');
            x[0].innerHTML += xmlhttp.responseText;
        }
        //verifica se uma função foi de fato passada, para então chama-la
        if(callback){
            callback.call();
        }
    }
}
function pegaSuporte(){
    requisicaoSincrona(9);

}
  requisicaoSincrona(6,pegaSuporte)

1 answer

4


When you do not initialize a variable it is in the global scope and can be modified by code at different places without leaving a trace. This causes very difficult errors to detect and is "prohibited" according to rules of good practice.

Initializes the variable with const or var if you need to support old browsers.

My suggestion is :

function requisicaoSincrona(categoria, modulo, destino, callback) {
  var xmlhttp = null;
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
  }
  var values = {
    modulo: modulo,
    categoria: categoria
  };
  var myJsonString = JSON.stringify(values);
  xmlhttp.onreadystatechange = respond;

  xmlhttp.open('POST', 'classes/getData.php', true);
  xmlhttp.send(myJsonString);
  //xmlhttp.abort();
  //como o código executado na volta da requisição é a função respond, chamamos o callback aqui
  function respond() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      destino.innerHTML += xmlhttp.responseText;
    }
    //verifica se uma função foi de fato passada, para então chama-la
    if (callback) callback.call();
  }
}
var x = document.getElementsByClassName('terceiraEtapa')[0];
requisicaoSincrona(6, modulo, x, function() {
  requisicaoSincrona(9, modulo, x);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.