I have a problem with the onreadystatechange when i make ajax request, it used to call the function but now it does not call the processRequest.
I am not sure if I edited something or what..Can sombody help..
function createAjaxObject(url, callback)
{
/// @par Implementation
var req = init();
req.onreadystatechange = processRequest;
/// @brief Creates a ajax object based on the runnunf browser
function init()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
/// @brief Checks if request is complete and HTTP call is successful
function processRequest ()
{
/// readyState of 4 signifies request is complete
if (req.readyState == 4){
/// status of 200 signifies sucessful HTTP call
if (req.status == 200){
if (callback)
callback(req.responseXML);
}
}
}
this.doPost = function(param) {
if (req.readyState == 4) {
/// make a HTTP GET request to the URL asynchronously
req.open("POST",url, true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.setRequestHeader("Content-length",param.length);
req.setRequestHeader("Connection", "close");
req.send(param);
}
}
}
thanks,
This line:
...(and the corresponding
}
) shouldn't be in the function you're assigning tothis.doPost
. E.g.:I'm assuming the way you use that is:
...because the code quoted never actually calls the function that does the post, but rather just assigns it to a property on
this
. The usual place you assign properties tothis
is within a constructor function, hence my usingnew
above.(BTW: The overwhelming convention in JavaScript code is to use initial caps on functions that are used as constructors, e.g.
CreateAjaxObject
[or better yet, justAjaxObject
] rather thancreateAjaxObject
.)There are a bunch of other changes I'd make to that code, but I think that's the minimum.
Side note: I'd recommend using a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over a lot of browser differences and provide a huge amount of well-tested utility functionality, letting you focus on what you actually need to do.