Simple Ajax hello world

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Hello Ajax World</title>
<script type="text/javascript">
 
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
 
function sendRequest()
{
var xhr = createXHR();
if (xhr)
{
xhr.open("GET","http://w3mentor.com/sayhello.php",true);
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
}
 
function handleResponse(xhr)
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var parsedResponse = xhr.responseXML;
var msg = parsedResponse.getElementsByTagName("message")[0].firstChild.nodeValue;
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = msg;
}
}
 
window.onload = function ()
{
document.getElementById("helloButton").onclick = sendRequest;
};
 
</script>
</head>
 
<body>
 
<form action="#">
<input type="button" value="Say Hello" id="helloButton" />
</form>
<br /><br />
<div id="responseOutput">&nbsp;</div>
 
</body>
</html>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.