I'm attempting to do some AJAX and need to know why this code isn't firing a completed or error alert. I'm in Mozilla Firefox 20.0.1
PLEASE NOTE
This code IS updating the database (I have a select statement reading the exact record verifying it's updating) I'm just unsure as to why I can't get an alert when the response has completed.
I have these GLOBAL (at the top of the javascript page) declared variables.
var AjaxEnginePage;
var ClientInfoPage;
var XMLHTTP;
AjaxEnginePage = "AjaxEngine.aspx";
ClientInfoPage="getClientInfo.aspx";
Creating the connection.
//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable
function CreateXMLHTTP()
{
try
{
XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
XMLHTTP = null;
}
}
//Creating object in Mozilla and Safari
if(!XMLHTTP && typeof XMLHttpRequest != "undefined")
{
XMLHTTP = new XMLHttpRequest();
}
}
Tying the connection:
function btnUpdateMe_OnClick() {
var me = encodeURIComponent(document.getElementById("MeTextBox").value);
// construct the URL
var requestUrl = AjaxEnginePage + "?Action=UpdateMe&Me=" + me;
CreateXMLHTTP();
// If browser supports XMLHTTPRequest object
if(XMLHTTP)
{
//Setting the event handler for the response
XMLHTTP.onreadystatechange = handleStateChange(me);
//Initializes the request object with GET (METHOD of posting),
//Request URL and sets the request as asynchronous.
XMLHTTP.open("get", requestUrl, true);
//Sends the request to server
XMLHTTP.send(null);
}
Handle State Change
function handleStateChange(me) {
switch (XMLHTTP.readyState) {
case 0: // UNINITIALIZED
case 1: // LOADING
case 2: // LOADED
case 3: // INTERACTIVE
break;
case 4: // COMPLETED
alert("Success");
break;
default: alert("error");
}
I can provide more code if needed. :( thanks.
The onreadystatechange property defines a function to be executed when the readyState changes. The status property and the statusText property holds the status of the XMLHttpRequest object.
readyState: 4: request finished and response is ready status: 200: "OK" When readyState is 4 and status is 200, the response is ready: since when xmlhttp.
A readystatechange occurs several times in the life of a request as it progresses to different phases, but a load event only occurs when the request has successfully completed. If you're not interested in detecting intermediate states or errors, then onload might be a good choice.
Change:
XMLHTTP.onreadystatechange = handleStateChange(me);
to:
XMLHTTP.onreadystatechange = function() {handleStateChange(me);};
You're setting onreadystatechange
to the result of calling the function, not to the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With