Problem in ajax

0

I'm not getting the answer to the ajax request. The code does not confirm whether it is working or not.

<script type="text/javascript">
    function iniciarAjax(){
        var ajax = false;
        if(window.XMLHttpRequest){
            ajax = new XMLHttpRequest();
        }else if(window.ActiveXObject){
            try{
                ajax = new ActiveXObject("Msxml2.XMLHttpRequest");
            }
            catch(e){
                try{
                    ajax = new ActiveXObject("Microsoft.XMLHttpRequest");
                }catch(ex){
                    ajax = false;
                }
            }
        }
        return ajax;
    }
    var conectarServidor = iniciarAjax();
    if(conectarServidor){
        conectarServidor.onreadystatechange = function(){
            if(conectarServidor.readyState == 4){
                if(conectarServidor.status == 200{
                    alert("Tudo certo")
                }
                else{
                    alert("Problema ocorreu")
                }
            }
            conectarServidor.open("GET","http://localhost/locadora/cadastro.php");
            conectarServidor.send();
        }
    }
</script>
    
asked by anonymous 07.07.2018 / 19:28

1 answer

1

The lines

conectarServidor.open("GET","http://localhost/locadora/cadastro.php");
conectarServidor.send();

You have to test out .onreadystatechange = function(){ because this is the function that will run when ajax starts to change its state. Having it in there will never run because .send() has never been executed.

function iniciarAjax() {
  var ajax = false;
  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      ajax = new ActiveXObject("Msxml2.XMLHttpRequest");
    } catch (e) {
      try {
        ajax = new ActiveXObject("Microsoft.XMLHttpRequest");
      } catch (ex) {
        ajax = false;
      }
    }
  }
  return ajax;
}
var conectarServidor = iniciarAjax();
if (conectarServidor) {
  conectarServidor.onreadystatechange = function() {
    if (conectarServidor.readyState == 4) {
      if (conectarServidor.status == 200) {
          alert("Tudo certo")
        } else {
          alert("Problema ocorreu")
        }
      }
    }
  }
  conectarServidor.open("GET", "http://localhost/locadora/cadastro.php");
  conectarServidor.send();
}
    
07.07.2018 / 19:52