Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  1] [ 5]  / answers: 1 / hits: 19618  / 12 Years ago, thu, may 17, 2012, 12:00:00

I'm trying to get an AJAX example working but i'm unable to get it working. Are you able to run it on XAMPP fine?



I've three files, message.txt, index.html, ajaxtest.js. When you click on the hyperlink it should bring up a pop up with the contents of message.txt. (all files are in the same directory)



index.html



<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>

<html>
<head>
<title> Using XMLHttpRequest</title>
<script type=text/javascript src=ajaxtest.js></script>
</head>
<body>
<p>
<a href=message.txt onclick=grabFile(this.href); return false;>
Click here
</a>
</p>
</body>
</html>


ajaxtest.js



function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) { //see if a XMLHttpRequest exists
xhr = new XMLHttpRequest(); //if it exists change xhr to a new instance of the object
}
else if (window.ActiveXObject) { //see if ActiveX exists (for IE)
try { //Allows newer versions of IE to use the newer ActiveX object
xhr = new ActiveXObject(Msxml2.AMLHTTP); //if it exists change xhr to a new instance of the object
}
catch(e) { //catches an error and resets xhr to false
try { //Allows older versions of IE to fall back onto the older version using try...catch
xhr = new ActiveXObject(Microsoft.XMLHTTP); //if it exists change xhr to a new instance of the object
}
catch(e) {
xhr = false;
}
}
}
return xhr;
}

function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
displayResponse(request);
};
request.open(GET, file, true);
request.send(null);
}
}

function displayResponse(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
alert(request.responseText);
}
}
}

More From » ajax

 Answers
3

As I have tried with your example , your request object is not hitting state 4 and using again .
check request.status before the below code, its getting 0 value always . And that's why you script is not alerting response .



if (request.status == 200 || request.status == 304) {
alert(request.responseText);
}


Check this for your solutions : http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/



Hope that help .


[#85525] Wednesday, May 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
daquanmilesw questions
;