0% found this document useful (0 votes)
9 views

Ajax

Uploaded by

Shlok Majmundar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Ajax

Uploaded by

Shlok Majmundar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter 3 : AJAX

Advanced Web Development 1


Introduction
• AJAX stands for Asynchronous JavaScript & XML
• It helps in creating better, faster & more interactive web applications
with the help of XML,HTML,CSS & JS
• It is not a programming language.
• It allows you to send and receive data asynchronously w/o reloading
the webpage.
• It allows you to send only important information to the server not the
entire page. So, it makes application interactive and faster.

Advanced Web Development 2


Working

3
Advanced Web Development
• AJAX makes use of a browser built-in XMLHttpRequest object to
request data from a Web Server and HTML DOM to display or use the
data.
• XMLHttpRequest Object : It is an API in the form an object whose
methods help in transfer of data between a web browser and a web
server.
• HTML DOM : When a web page is loaded, the browser creates a
Document Object Model of the page.

Advanced Web Development 4


XMLHttpRequest
• An object of XMLHttpRequest is used for asynchronous
communication between client and server.
• It performs following operations:
1. Create an XMLHttpRequest object
2. Define a callback function
3. Open the XMLHttpRequest object
4. Send a Request to a server

5
Properties
Property Description
onReadyStateChange It is called whenever readystate attribute changes. It must not be used with
synchronous requests.
readyState represents the state of the request. It ranges from 0 to 4

0 UNOPENED open() is not called.


1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and status are
available.
3 LOADING Downloading data; responseText holds the data.
4 DONE The operation is completed fully.

reponseText returns response as text.


responseXML returns response as XML

Advanced Web Development 6


Response Properties

Property Description
status 200:"OK"
403: "Forbidden"
404: "Page not found“
Many others
statusText Returns the status-text (e.g. "OK" or "Not Found")

Advanced Web Development 7


Methods
Methods Description
open(method, URL) opens the request specifying get or post method and
url.
open(method, URL, async) same as above but specifies asynchronous or not.
open(method, URL, async, username, password) same as above but specifies username and password.
send() sends get request.
send(string) send post request.
setRequestHeader(header,value) it adds request headers.

Advanced Web Development 8


Sending Request and Retrieving the Response
• Before performing ajax communication between client & server, an
XMLHTTPRequest object is initialized.
var request = new XMLHttpRequest();
• Then, the newly created request object using the open() method of
XMLHTTPRequest object is instantized.
• The open() method accepts two parameters--- the http request
method to use & url to send the request
request.open("GET", "info.txt");
request.open(“POST”, “info.txt”);

9
• Finally sends the request to server using the send() method of the
XMLHTTPRequest object.
request.send();
request.send(body);
Here, the body parameter allows us to specify the request’s body. This is primarily
used for HTTP POST requests.

10
GET & POST Methods

• The GET method is generally used to send small amount of data to


the server. Whereas, the POST method is used to send large amount
of data.
• In GET method, the data is sent as URL parameters. But, in POST
method, the data is sent to the server as a part of the HTTP request
body. Data sent through POST method will not visible in the URL.

11
• The GET request is typically used to get or retrieve some kind of
information from the server that doesn't require any manipulation
or change in database.
• For example, fetching user details based on their id or name.
• Post method is mainly used to submit a form data to the web
server

12
• GET is simpler and faster than POST, and can be used in most cases.
• However, always use POST requests when:
• We update a file or database on the server.
• Sending a large amount of data to the server.
• POST is more robust and secure than GET for sending user input.

13
EXAMPLE: GET Method
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; }
xhttp.open("GET", "demo.txt");
xhttp.send();
}
</script>
</body>
</html>
14
EXAMPLE: POST Method
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; }
xhttp.open("POST", "demo.txt");
xhttp.send();
}
</script>
</body>
</html>
15
Handling Server Responses
• There are several response attributes defined by the standard
specification for the XMLHTTPRequest() constructor.
• responseText: It returns the server response as a JavaScript string.
• responseXML: It returns the server response as an XML DOM object.
• These attributes tell the client making the XMLHttpRequest important
information about the status of the response.
• Some cases where dealing with non-text response types may involve
some manipulation.

16
Example: responseText
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change
Content</button>
</div>

<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.open("GET", “demo.txt");
xhttp.send();
}
</script>
</body>
</html>
17
Response Methods

Methods Description
getResponseHeader() returns all header information from the server response.
getAllResponseHeaders() Returns all the header information from the server resource

Advanced Web Development 18


Example: responseXML
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<p id="demo"></p>
<script>
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const xmlDoc = this.responseXML;
const x = xmlDoc.getElementsByTagName("ARTIST");
let txt = "";
for (let i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
</script>

</body>
</html>
19
jQuery ajax() Method
• The jQuery ajax() method provides core functionality of Ajax in
jQuery. It sends asynchronous HTTP requests to the server.
$.ajax(url);
$.ajax(url, option);
• url: A string URL to which you want to submit or retrieve the data
• options: Configuration options for Ajax request. An options parameter
can be specified using JSON format. This parameter is optional.

20
Send Ajax Request
• The ajax() methods performs asynchronous http request and gets the data
from the server. The following example shows how to send a simple Ajax
request.
• Example:
$.ajax(‘/jquery/getdata’, {
url: "demo_test.txt"
success: function(data,status,xhr{
$(‘p’).append(‘data’);
})
})

21
jQuery Get Method
• Sends asynchronous HTTP request to the server and retrieves the
data.
• Syntax:
$.get(url, data, callback);
• url: request url from which you want to retrieve the data
• data: data to be sent to the server with the request as a query string
• callback: function to be executed when request succeeds

22
Example
$.get('/data.txt',
function (data, textStatus, jqXHR) {
alert('status: ' + textStatus + ', data:' + data);
});

23
jQuery Post Method
• The jQuery post() method sends asynchronous http POST request to
the server to submit the data to the server and get the response.
• Syntax:
$.post(url,data,callback,type);
• url: request url from which you want to submit & retrieve the data.
• data: data to be sent to the server with request as a form data.
• callback: function to be executed when request succeeds.
• type: data type of the response content.

24
Example
$.post('/jquery/submitData',
{ myData: 'This is my data.' },
function(data, status, jqXHR) {
$('p').append('status: ' + status + ', data: ' + data);
})

25
jQuery load Method
• The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.
• Syntax:
$.load(url,data,callback);
• url: request url from which you want to retrieve the content
• data: data to be sent with request to the server.
• callback: function to be executed when request succeeds

26
• Example: $('#msgDiv').load('/demo.html');
• If no element is matched by the selector then Ajax request will not be
sent.
• The load() method allows us to specify a portion of the response
document to be inserted into DOM element.
• This can be achieved using url parameter, by specifying selector with
url separated by one or multiple space characters
• Example: $('#msgDiv').load('/demo.html #myHtmlContent');

27
• The load() method also allows us to specify data to be sent to the
server and fetch the data.
• Example:
$('#msgDiv').load('getData',
{ name: 'bill' },
function(data, status, jqXGR) {
alert('data loaded')
});

28
Ajax DataType
• In jQuery $.ajax() method dataType is a parameter that tells what kind
of response is expected.
• If datatype is specified in $.ajax() method, the method will set
Accept of Request Headers to corresponding value of the datatype.
• When the data returns from the server ,jquery tries convert the data
passed by server to the specified type.
• If none is specified, jQuery will try to infer it based on the MIME type
of the response (an XML MIME type will yield XML, in 1.4 JSON will
yield a JavaScript object, in 1.4 script will execute the script, and
anything else will be returned as a string).
29
Ajax Datatypes
1. xml : Returns a XML document that can be processed via jQuery.
2. html: Returns HTML as plain text; included script tags are evaluated
when inserted in the DOM.
3. script: Evaluates the response as JavaScript and returns it as plain
text.
4. json: Evaluates the response as JSON and returns a JavaScript
object.
5. jsonp: Loads in a JSON block using JSONP.
6. text: a plain text string

30

You might also like