I recently ran into problems using Javascript’s readyState property in Internet Explorer (IE). I was using XMLHttpRequest, http.open and http.send to make a call to a PHP / MySQL script. If the MySQL was executed correctly, the PHP would return the value “1″. If the Javascript saw that “1″ value, it would then send an alert that said “Your query was successful” - the problem was, Internet Explorer did not instantly get the readyState.
I was receiving an error that said “The data necessary to complete this operation is not yet available”.
Here’s the original code, which works in Firefox but not in Internet Explorer (IE).
// Create the XMLHttpRequest
var http = new XMLHttpRequest();// Open the XMLHttpRequest
http.open(’get’, ‘/url/mypage.php’, true);// Send the XMLHttpRequest
http.send(null);// If the PHP code returns a value of “1″
if (http.responseText == ‘1′) { alert(’Your query was successful.’); }
I tried checking the readyState along with my current IF Statement, but received similar errors:
if (http.readyState == 4 && http.responseText == ‘1′) { alert(’Your query was successful.’); }
After trying several different things, I discovered that Internet Explorer uses a ActiveXObject instead of XMLHttpRequest. As a result, I had to add aditional code, which finds out what browser the visitor is using, and then uses the correct function (ActiveXObject or XMLHttpRequest) depending on their particular browser. The rest of the code remains the same:
// Get the visitor’s browser information
var browser = navigator.appName;// If the visitor is using IE, then use ActiveXObject
if (browser == “Microsoft Internet Explorer”) {
var http = new ActiveXObject(”Microsoft.XMLHTTP”);
} else { var http = new XMLHttpRequest(); }// Open the XMLHttpRequest
http.open(’get’, ‘/url/mypage.php’, true);// Send the XMLHttpRequest
http.send(null);// Wait for the readyState
if (http.readyState == 4) {// If the PHP code returns a value of “1″
if (http.responseText == ‘1′) { alert(’Your query was successful.’); }}

