Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

JS

p10
definition

Asynchronous JavaScript + XML, while not a technology in


itself, is a term coined in 2005 by Jesse James Garret
definition

AJAX stands for Asynchronous JavaScript And XML. It is the


use of the XMLHttpRequest object to communicate with
servers.
It can send and receive information in various formats,
including JSON, XML, HTML, and text files. AJAX’s most
appealing characteristic is its "asynchronous" nature, which
means it can communicate with the server, exchange data,
and update the page without having to refresh the page.
technologies

AJAX it is a set of technologies that are supported by web browsers


AJAX uses
HTML
CSS
DOM
XMLHttpRequest
JavaScript
pros

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
How AJAX Works

An event occurs in a web page


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
The features of AJAX

Make requests to the server without reloading the


page
Receive and work with data from the server
Step 1 – How to make an HTTP request

In order to make an HTTP request to the server with JavaScript, you need an instance of
an object with the necessary functionality. This is where XMLHttpRequest comes in.

if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...


httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
Step 1 – How to make an HTTP request

After making a request, you will receive a response back. At this stage, you need to tell
the XMLHttp request object which JavaScript function will handle the response

httpRequest.onreadystatechange = nameOfTheFunction;
or
httpRequest.onreadystatechange = function(){
// Process the server response here.
}
XMLHttpRequest Object Methods

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
Send a Request To a Server

after declaring what happens when you receive the response, you need to actually make
the request, by calling the

open() and send()


methods of the HTTP request object

httpRequest.open('GET', 'http://www.example.org/some.file', true);


httpRequest.send()
open()

open()
request.open("GET", // request method HTTP GET/POST
"data.csv”, // URL
true); // asynchronous/synchronous

1 The first parameter of the call to open() is the HTTP request method –
GET, POST, HEAD, or another method supported by your server
2 The second parameter is the URL you're sending the request to. As a
security feature, you cannot call URLs on 3rd-party domains by default.
3 The optional third parameter sets whether the request is
asynchronous. This is the first A in AJAX. true (the default).
GET or POST

GET is simpler and faster than POST, and can be used in most cases.

Always use POST requests when:

• A cached file is not an option (update a file or database on the server).


• Sending a large amount of data to the server (POST has no size limitations).
• Sending user input (which can contain unknown characters), POST is more robust and
secure than GET.
GET Requests
POST Requests

Method Description
setRequestHeader(header, value) Adds HTTP headers to the request

header: specifies the header name


value: specifies the header value
Asynchronous

Server requests should be sent asynchronously.

The async parameter of the open() method should be set to true

xhttp.open("GET", "ajax_test.asp", true);
Synchronous Request

xhttp.open("GET", "ajax_info.txt", false);

Sometimes async = false are used for quick testing.

Synchronous XMLHttpRequest (async = false) is


not recommended because the JavaScript will stop
executing until the server response is ready

Modern developer tools are encouraged to warn


about using synchronous requests and may throw
an InvalidAccessError exception when it occurs
send()

The parameter to the send() method can be any data you want to send to the server if
POST-ing the request. Form data should be sent in a format that the server can parse

"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

if you want to POST data, you may have to set the MIME type of the request. For
example, use the following before calling send() for form data sent as a query string

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Step 2 – Handling the server response

When you sent the request, you provided the name of a JavaScript
function to handle the response

httpRequest.onreadystatechange = nameOfTheFunction;

the function needs to check the request's state.

if (httpRequest.readyState === XMLHttpRequest.DONE) {


// Everything is good, the response was received.
} else {
// Not ready yet.
}
 XMLHTTPRequest

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


onreadystatechange

With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.
The function is defined in the onreadystatechange property of the XMLHttpResponse object
Server Response Properties

After checking the state of the request and the HTTP status code of the
response,
you can do whatever you want with the data the server sent.
You have two options to access that data:
•httpRequest.responseText – returns the server response as a string of text
•httpRequest.responseXML – returns the response as an XMLDocument 
object you can traverse with JavaScript DOM functions
responseText

function start(){
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if (xhttp.readyState==4 && xhttp.status==200)
document.getElementById('ajax').innerHTML=xhttp.responseText;
}
xhttp.open('GET','testfile.txt',true);
xhttp.send();
}
responseXML

var xmldoc = httpRequest.responseXML;


var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
Server Response Methods

Method Description

getResponseHeader() Returns specific header information from the server resource

getAllResponseHeader Returns all the header information from the server resource
s()
JSON

function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var response = JSON.parse( httpRequest. responseText);
alert(response.computedString);
} else {
alert('There was a problem with the request.');
}}}
example

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

You might also like