I am new to AJAX and presently learning it from Head First AJAX
. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.
main.js
window.onload = initPage;
function initPage() {
request = createRequest();
if(request == null) {
alert("request could not be created");
}
else {
var url = "requestMe.php";
request.onreadystatechange = showResult;
request.open("GET", url, true);
request.send(null);
}
}
function showResult() {
if(request.readyState == 4) {
if(request.status == 200) {
if(request.responseText == "okay") {
alert("A successful request was returned");
}
else {
alert("ALERT : " + request.responseText);
}
}
else {
alert("Request status received was not correct");
}
}
}
//--function to create request objects--
function createRequest(){
try{
request = new XMLHttpRequest();
}
catch(tryMS){
try{
request = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request = null;
}
}
}
return request;
}
Now, here is the php script.
requestMe.php
<?php
echo 'okay';
?>
This code should give the alert A successful request was returned
But instead it gives the result ALERT : okay
The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText
received is correct because it appends okay
after ALERT :
. What wrong am I doing here in the code? Why is it going to the else
part when the responseText
received is correct?
Any Help? Thanks in advance.