Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript array empty outside a function

I have JavaScript code like this:

var buffer=new Array();

function fetchData(min,max){
    var ajaxReq = new XMLHttpRequest(); 
    ajaxReq.onreadystatechange = function(){
    if (ajaxReq.readyState === 4) {
        if (ajaxReq.status === 200) {
            buffer= ajaxReq.responseText;
            console.log(buffer)//this logs an array to console
        } else {
            console.log("Error", ajaxReq.statusText);
        }
    }
    };
    ajaxReq.open('GET', "server/controller.php?min="+min+"&max="+max, true); 
    ajaxReq.send();
}

fetchData(1,100);
console.log(buffer);//this log an empty array

two logs with different result, what am I doing wrong? thanks for pointers.

like image 382
bingjie2680 Avatar asked Jun 30 '26 03:06

bingjie2680


2 Answers

Ajax is asynchronous. That means that console.log(buffer) at the end is executed before the response from the Ajax request.

You should change your method to this:

function fetchData(min,max,callback){
  var ajaxReq = new XMLHttpRequest(); 
  ajaxReq.onreadystatechange = function(){
    if (ajaxReq.readyState === 4) {
      if (ajaxReq.status === 200) {
        buffer= ajaxReq.responseText;
        callback();
        //console.log(buffer)//this logs an array to console
      } else {
        console.log("Error", ajaxReq.statusText);
      }
     }
  };
  ajaxReq.open('GET', "server/controller.php?min="+min+"&max="+max, true); 
  ajaxReq.send();
}

fetchData(1,100,function(){
    console.log("My Ajax request has successfully returned.");
    console.log(buffer);
});
like image 86
JP Richardson Avatar answered Jul 01 '26 17:07

JP Richardson


You are trying to log() the buffer before the AJAX request in executed. To solve this, your fetchData function needs to handle a callback function.

var buffer=new Array();

function fetchData(min,max, callback){
    var ajaxReq = new XMLHttpRequest(); 
    ajaxReq.onreadystatechange = function(){
    if (ajaxReq.readyState === 4) {
        if (ajaxReq.status === 200) {
            buffer= ajaxReq.responseText;
            console.log(buffer)//this logs an array to console
            if(typeof callback == 'function'){
                callback.call(this);
            }
        } else {
            console.log("Error", ajaxReq.statusText);
        }
    }
    };
    ajaxReq.open('GET', "server/controller.php?min="+min+"&max="+max, true); 
    ajaxReq.send();
}

fetchData(1,100, function(){
    console.log(buffer);
});

This is the most basic implementation, and will work only if the AJAX response is successful.

like image 35
Pierre Avatar answered Jul 01 '26 16:07

Pierre