xmlhttp is not defined

Asked

Viewed 36 times

0

I’m having some problems when performing an ajax request by javascript, however, it appears that the variable xmlhttp was not defined, even though I defined 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;
    };
};
  • Giving a.log console(xmlhttp) I receive all zeroed or null values

1 answer

4


The problem is that you are creating a local variable in generateMessage, so she’s 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 cannot 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 in xmlhttp.onreadystatechange, is calling the function even before the request is opened.

To assign a function you need 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 );
    }
};
  • so now stopped presenting errors but still not working :/

  • 1

    It may be that the status code your page is different from 200 OK. Add, in the function callbackChampMessage, one console.log(xmlhttp); before the if.

  • 1

    @Murilogambôa, I edited my answer. Passed beaten previously.

  • Just removing the parentheses from the callback call worked, I had seen this error and forgot to remove

Browser other questions tagged

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