0% found this document useful (0 votes)
34 views30 pages

Ajax

Study Material vol 3

Uploaded by

ranotego
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views30 pages

Ajax

Study Material vol 3

Uploaded by

ranotego
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

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:

● Update a web page without reloading the page


● Request data from a server - after the page has loaded
● Receive data from a server - after the page has loaded
● Send data to a server - in the background
AJAX allows web pages to be updated asynchronously
by exchanging small amounts of data with the server
behind the scenes. This means that it is possible to
update parts of a web page, without reloading the
whole page.

Classic web pages, (which do not use AJAX) must reload


the entire page if the content should change.

Examples of applications using AJAX: Google Maps,


Gmail, Youtube, and Facebook tabs.
• An object of XMLHttpRequest is used for
asynchronous communication between client
and server.
• It performs following operations:
• Sends data from the client in the background
• Receives the data from the server
• Updates the webpage without reloading it.
• Ajax uses XHTML for content, CSS for
presentation, along with Document Object
Model and JavaScript for dynamic content
display.
How AJAX Works
working
1. An event occurs in a web page (the page is loaded, a
button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web
server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by
JavaScript
• AJAX is Based on Open Standards
• AJAX is based on the following open standards:
• Browser-based presentation using HTML and
Cascading Style Sheets (CSS).

• Data is stored in XML format and fetched from


the server.
• Behind-the-scenes data fetches using
XMLHttpRequest objects in the browser.
• JavaScript to make everything happen.
• AJAX cannot work independently. It is used in
combination with other technologies to create interactive
webpages.
• JavaScript
• Loosely typed scripting language.
• JavaScript function is called when an event occurs in a
page.
• Glue for the whole AJAX operation.
• DOM
• API for accessing and manipulating structured
documents.
• Represents the structure of XML and HTML documents.
• CSS
• Allows for a clear separation of the presentation style
from the content and may be changed programmatically
by JavaScript.
The XMLHttpRequest Object
The XMLHttpRequest is a part of standard JavaScript. You don’t have to load a
library to use it, and it doesn’t require any special syntax to use.

You start out by calling the XMLHttpRequest constructor using the new keyword
and storing the resulting object in a variable:

var ajaxRequest = new XMLHttpRequest();


• XMLHttpRequest
• JavaScript object that performs asynchronous
interaction with the server.
• The XMLHttpRequest Object
• All modern browsers support the
XMLHttpRequest object (IE5 and IE6 use an
ActiveXObject).
• The XMLHttpRequest object is used to
exchange data with a server behind the
scenes. This means that it is possible to
update parts of a web page, without reloading
the whole page.
Create an XMLHttpRequest Object

• All modern browsers (IE7+, Firefox, Chrome,


Safari, and Opera) have a built-in
XMLHttpRequest object.

• variable=new XMLHttpRequest();
Then you set the onreadystatechange property of the object you
just created. The onreadystatechange points to a function that will
be called as the external file is loaded:
ajaxRequest.onreadystatechange = function(){
console.log("Ready state changed!");
//more on this in a second
}
Then you call the open() function and pass it 3 parameters:
● The first parameter is what type of request this should be. We want to
get some content, so we’ll use "GET" for now. Later you might use
"POST" if you want to post content to a server.
● The second parameter is the URL that contains the stuff you want to
load.
● The third parameter is a boolean: true if you want your code to keep
going while the content is loaded, false if you want the code to stop and
wait for the loading to finish. At this point you should always use true,
otherwise your page can become unresponsive while the URL is
loaded.
Finally, you call the send() function to send the request
to the URL you specified.

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

Specifies the type of request, the URL, and if the


request should be handled asynchronously or
not.
open(method,url,asyn
c) method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false
(synchronous)

Sends the request off to the server.


send(string)
string: Only used for POST requests
Example
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
console.log("Ready state changed!");
//more on this in a second
}
ajaxRequest.open("GET", "https:/………../text-welcome.txt", true);
ajaxRequest.send();
• Async=true
• When using async=true, specify a function to
execute when the response is ready in the
onreadystatechange event:
AJAX - Server Response

• Server Response
• To get the response from a server, use the
responseText or responseXML property of the
XMLHttpRequest object.
Property Description

responseText get the response data as a string


responseXML get the response data as XML data
AJAX - The onreadystatechange Event

The onreadystatechange property defines a


function to be executed when the readyState
changes.

The status property and the statusText property


holds the status of the XMLHttpRequest
object.
Property Description
onreadystatechange Defines a function to be called when the
readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the
Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not


Found")
<!DOCTYPE html> <html><head><script>

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>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>


<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body></html>
Ajax and json
<script>
function getWelcome(){

var ajaxRequest = new XMLHttpRequest();


ajaxRequest.onreadystatechange = function(){

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);

//get random object from array


var randomIndex = Math.floor(Math.random()*messagesArray.length);
var messageObj = messagesArray[randomIndex];

//use that object to set content and color


var welcomeDiv = document.getElementById("welcome");
welcomeDiv.innerHTML = messageObj.text;
welcomeDiv.style.color = messageObj.color;
}
else{
console.log("Status error: " + ajaxRequest.status);
}
}
else{
console.log("Ignored readyState: " + ajaxRequest.readyState);
}
}
ajaxRequest.open('GET', 'randon-welcomes.json');
ajaxRequest.send();
}

</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>

You might also like