Ajax
Ajax
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.
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
Property Description
status 200:"OK"
403: "Forbidden"
404: "Page not found“
Many others
statusText Returns the status-text (e.g. "OK" or "Not Found")
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
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
</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