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.
Do one thing add exit; after echo 'okay';
Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.
I hope it will fix your issue.
I personally would do it using jQuery's Ajax Function in the following way:
document.addEventListener("DOMContentLoaded", function()
{
$.ajax({
"url": "requestMe.php"
}).done(function(data)
{
if(data == "okay")
{
alert("A successful request was returned");
} else
{
alert("ALERT : " + data);
}
}).fail(function()
{
alert("Connection Failed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I haven't tested this Script, but it should in theory work out well.
</div>