JavaScript XMLHttpRequest.onreadystatechange
ajax, javascript, xmlhttprequest
Solution
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.
Problem
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.