var ajax = {
xmlHTTP: function() {
xml = new XMLHttpRequest();
return xml;
},
xmlHTTPfunction: function() {
if (xml.readyState == 4 && xml.status == 200) {
document.getElementById("te").innerHTML = xml.responseText;
alert(xml.status);
alert(xml.responseText);
}
},
xmlHTTPopen: function(url) {
xml.open("POST", url, true);
},
xmlHTTPheader: function() {
ajax.xmlHTTP().setRequestHeader("Content-type","application/x-www-form-urlencoded");
},
xmlHTTPsend: function(string) {
xml.send(string);
},
ajaxCall: function() {
ajax.xmlHTTP();
ajax.xmlHTTPopen('testx.php');
ajax.xmlHTTPsend('test');
return 1;
}
}
if(ajax.ajaxCall() == 1) {
document.getElementById("te").innerHTML = xml.responseText;
}
var ajax = { xmlHTTP: function() { xml = new XMLHttpRequest(); return xml; },
Share
Most of the functions refer to the
xmlvariable which is poorly scoped. That is to say, when you callajax.xmlHTTPopenthere’s nothing to say that the xml variable has any value inside said function.The simplest way to provide better scoping would be to define the xml variable as a property of the ajax object; here is an example with minimal changes to your code:
Note that, as you’ve written it, the
ajax.ajaxCallis non-blocking, so it will always return 1 immediately, even before the response arrives (or is necessarily sent) — to that end, you have to assign a callback function to the XMLHtpRequest object’s onreadystatechange event, to handle the response when it eventually comes back.If you change the third parameter of
xml.opentofalsethe xml.send call will block until a response arrives, in which case you don’t need to assign a callback. The alternative implementation may look like this:However in my experience, this is almost never used in the real world.
Also: your code never calls the xmlHTTPheader function, although there’s no harm in that.
I can’t think of a better proposal given your current code; have you looked at jQuery and its implementation of ajax?