1

I am using XMLHttpRequest in side javascript code.

I am using jquery-1.7.1.

If I am using alert after XMLHttpRequest then the next code work smoothly but when removing that alert the next statement is not getting value of variable which is initialize inside the XMLHttpRequest block.

Following is the code which I am using

var dyn_data='';
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
{
    xmlhttp = new XMLHttpRequest();
}
if (xmlhttp) 
{ 
    var query = 'ACTION=test&format=text';
    xmlhttp.open('POST', 'sample.php'); 
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.send(query); 
    xmlhttp.onreadystatechange = function() 
        { 
            var arrayindex=0;

            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
            {
                dyn_data=xmlhttp.responseText;
            }
        }
}
var obj = $.parseJSON(dyn_data);
alert(obj);
var data=obj;

If I am commenting alert in above code then it is not working.

I tried following statement at place of alert but it is also not work for me.

setTimeout(function(){  }, 5000);

Any help/suggestion would be appreciated.

Rushika Patel
  • 95
  • 1
  • 8

1 Answers1

1

The XMLHttpRequest is asynchronous. This means that the dyn_data value has not been set before the $.parseJSON line is reached. All code which relies on the response should be placed in the onreadystatechange handler. Try this:

var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
}
else if (xmlhttp) { 
    var query = 'ACTION=test&format=text';
    xmlhttp.open('POST', 'sample.php'); 
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.send(query); 
    xmlhttp.onreadystatechange = function() { 
        var arrayindex = 0;
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var obj = $.parseJSON(xmlhttp.responseText);
            console.log(obj);
            var data = obj;
        }
    }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339