0

I was trying to write an AJAX class in javascript mainly for learning purposes and I've encountered this problem that I haven't been able to solve.

I wanted to pass whatever AJAX response triggered by onreadystatechange to a class property for further use but the property returns null in every different way I tried to format the code.

I think it has something to do with scopes and/or execution order, but I simply can't figure it out.

Example:

function Ajax() {
    var self = this;
    this.response = null; //the property in question
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            self.response = xmlhttp.responseText; //responseText is set; it works only here
        }
    };
    xmlhttp.open("POST", "foo.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("foo=bar");
}
var ajax = new Ajax();
alert(ajax.response); //returns the default value

The php file only contains a print, since this is an example:

<?php
    print_r($_POST);

I tried passing the xmlhttp object to a separate method but that didn't work either.

Storing the xmlhttp object as a property of the class also doesn't work, it doesn't set the property because it doesn't even go past status 0 for some reason.

I'd appreciate if someone explained what I am missing or misunderstanding here. Thanks for your time.

Dante
  • 263
  • 2
  • 14
  • `xmlhttp.onreadystatechange` is called asynchronously, which means after your current "Execution Context". So the order of operations is as follows: `var ajax = new Ajax()`, `alert(ajax.response)`, your current execution context ends, and some time after that, `xmlhttp.onreadystatechange` is called. – Sacho Mar 28 '16 at 13:04
  • So then it's an issue with the execution order. Any suggestion for how to solve it? – Dante Mar 28 '16 at 13:07

0 Answers0