Ajax
Ajax
• What is AJAX?
• AJAX = Asynchronous JavaScript and XML.
• AJAX is a technique for creating fast and dynamic web
pages.
AJAX is a way to access external files from your webpage, but it
doesn’t work with files on your file system. The files you access has to
be on the internet:
You start out by calling the XMLHttpRequest constructor using the new keyword
and storing the resulting object in a variable:
The browser will fetch the contents and then call the
onreadystatechange function you set.
AJAX - Send a Request To a Server
• To send a request to a server, we use the
open() and send() methods of the
XMLHttpRequest object:
• xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Method Description
• Server Response
• To get the response from a server, use the
responseText or responseXML property of the
XMLHttpRequest object.
Property Description
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script></head><body>
</body></html>
Ajax and json
<script>
function getWelcome(){
if(ajaxRequest.readyState == 4){
//the request is completed, now check its status
if(ajaxRequest.status == 200){
//turn JSON into array
var messagesArray = JSON.parse(ajaxRequest.responseText);
</script>
</head>
<body onload="getWelcome()">
<div id="welcome"></div>
<p>This is an example website.</p>
<img
</body>
</html>
Example
Q Display wikipedia data on button click .about
Albert Einstein.
(using AJAX)
<div>
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/Einstein.jpg" alt="Einstein">
<button id="request">Learn more about Einstein</button>
<div id="bio"></div>
</div>
<script>
(function() {
var btn = document.getElementById('request');
var bio = document.getElementById('bio');
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
bio.innerHTML = request.responseText;
} else {
bio.innerHTML = 'An error occurred during your request: ' + request.status + ' ' +
request.statusText;
} } }
request.open('Get', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/Bio.txt');
btn.addEventListener('click', function() {
// hide the button
this.style.display = 'none';
// send the request
request.send();
}); })();</script>