0

i have i think a global variable problem. Watch this:

function more_elems() {
var ret = [];

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
    {

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var JSONObject = JSON.parse(xmlhttp.responseText);
for (i=0;i<5;i++){
    ret[i] =
    {
    id: JSONObject[i].id,
    nombre: JSONObject[i].nombre,
    mensaje: JSONObject[i].mensaje,
    ult_m: JSONObject[i].ultima_modificacion
    };

}
alert(ret);
}
    }
xmlhttp.open("GET","somewesite.com",true);
xmlhttp.send();
return ret;

So im trying to return the ret array but it returns undefined. However if i do an alert inside the xmlhttp.onreadystatechange=function() it does show the array with the json object. I'm not sure what the problem is =/.

Thanks in advance.

  • 1
    you need to understand what a callback is ... http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o – rafaelcastrocouto Feb 26 '14 at 19:54
  • Even tough your variable scope is correct, take a look at [this](http://stackoverflow.com/q/500431/2752041). It might help you understand better variables scopes and globals. ;) – mathielo Feb 26 '14 at 19:55

1 Answers1

0

Ajax is asynchronous. So the ret array will not be set when you invoke immediately after xmlhttp.send().

Have any mehtod and pass the value once the value of ret array is set. Ty something like below,

xmlhttp.onreadystatechange=function()
    {

        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             var JSONObject = JSON.parse(xmlhttp.responseText);
             for (i=0;i<5;i++){
            ret[i] ={
               id: JSONObject[i].id,
               nombre: JSONObject[i].nombre,
               mensaje: JSONObject[i].mensaje,
               ult_m: JSONObject[i].ultima_modificacion
            };

        }
        onAjaxSuccess(ret);
      }
    }

function onAjaxSuccess(arr){
    alert(arr);
}
Subash Selvaraj
  • 3,385
  • 1
  • 14
  • 17
  • Yup , that works! thanks. But what if im trying to return ret on the main function -> function more_elems(). 'Cause that is what im trying to achieve. Returning ret array on that function. – Carlos Peña Feb 26 '14 at 20:09
  • Hope it helped. You cant do that as I said Ajax is asynchronous and by the time you return at the end of the function the `ret array` wont be set with the values. Hope it helped. Don't mind to mark it as correct answer ;) – Subash Selvaraj Feb 26 '14 at 20:17
  • Right.. well i'll have to figure out how to do it then. Thanks and will do :) – Carlos Peña Feb 26 '14 at 20:20