0

I have trouble with using variables in AJAX. I want var x to remember data from var data. However when I check in the console log the value is undefined. Can somebody help me with this? EDIT: I need to use the variable x later in the code. It's not just about checking the value.

var x;

var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var results = new Array();
            var numberOfSuggestions = 0;

            var data = xmlhttp.responseText;                
            var data = eval(data);
            x = data;

            /*
            some code
            */
        }
    }
console.log(x);

2 Answers2

0

You are outputting variable x outside the callback function of the xmlhttp.onreadystatechange event, which will only be called, when the event triggers.

In order to see the value assigned to x after the Request completed, put your console.log into the callback function.

var x;

var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var results = new Array();
            var numberOfSuggestions = 0;

            var data = xmlhttp.responseText;                
            var data = eval(data);
            x = data;
            console.log(x);
            /*
            some code
            */
        }
    }
Exinferis
  • 689
  • 7
  • 17
  • Ok, but i want to use the variable x later on. It's not about seeing the x value. It's about saving the value for later. –  Jan 13 '15 at 13:51
  • 1
    Either use a synchronous ajax call - using jQuery for example - or use the callback to trigger the next function needed. I think you need to seriously learn about async programming. Something like this: http://recurial.com/programming/understanding-callback-functions-in-javascript/ – Exinferis Jan 13 '15 at 13:54
0

As AJAX is asynchronous, your console.log(x) is executed before the response is ready to be evaluated. You have to write the var x dependent code synchronously. You can put the code that uses var x in a function and then call that function after the response is ready and can be evaluated.

var x;

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var results = new Array();
        var numberOfSuggestions = 0;

        var data = xmlhttp.responseText;                
        var data = eval(data);
        x = data;

        /*
        var x dependent code 
              OR
        xdependentFunc(x);
        */
    }
}

function xdependentFunc(x){
  /*
   use x...............
  */
}
console.log(x);
Krishna
  • 5,194
  • 2
  • 28
  • 33