xmlhttp is not defined

0

I'm having some problems while performing an ajax request by javascript, however, it does appear that the variable xmlhttp has not been defined, even though I set it before the function and before using it. How to solve?

var xmlhttp;
function generateMessage(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackChampMessage();
    var url = "randomName.php";
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
};
function callbackChampMessage(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var messageHeader = document.querySelector("#champ-message");
        champMessage.innerHTML = xmlhttp.responseText;
    };
};
  • Given a console.log (xmlhttp) I get the values all zeroed or null
asked by anonymous 10.01.2018 / 12:57

1 answer

4

The problem is that you are creating a local variable in generateMessage , so it is not assigning the value to the global variable.

When you define a variable within the scope of the function or redeclared it, it becomes local and can not be accessed outside the function.

// Global
var global = 0;

function myFunc() {
    // O js cria uma variável local
    var global = 3;
}

myFunc();
console.log( global ); //Output: 0

Another error is that you, instead of assigning the function callbackChampMessage to xmlhttp.onreadystatechange , are calling the function even before the request is opened.

To assign a function, it is necessary to pass only its name.

Example:

var xmlhttp;

function generateMessage(){

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackChampMessage;
    var url = "https://example.com/";
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

};

function callbackChampMessage(){
    console.log( xmlhttp );

    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var messageHeader = document.querySelector("#champ-message");
        champMessage.innerHTML = xmlhttp.responseText;
    } else {
        alert( "Ready State: " + xmlhttp.readyState );
        alert( "Status: " + xmlhttp.status );
        alert( "Status: " + xmlhttp.responseURL );
    }
};
    
10.01.2018 / 13:01