0% found this document useful (0 votes)
187 views47 pages

Making Ajax Queries

The document discusses JavaScript and Ajax. It provides an introduction to Ajax, explaining that Ajax allows asynchronous communication with servers in the background without interfering with page display. It covers using the XMLHttpRequest object to make Ajax requests, including properties like readyState and methods like open() and send(). It also discusses Fetch API, jQuery methods for Ajax like ajax(), load(), get(), and post(), and includes examples of GET and POST requests.
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)
187 views47 pages

Making Ajax Queries

The document discusses JavaScript and Ajax. It provides an introduction to Ajax, explaining that Ajax allows asynchronous communication with servers in the background without interfering with page display. It covers using the XMLHttpRequest object to make Ajax requests, including properties like readyState and methods like open() and send(). It also discusses Fetch API, jQuery methods for Ajax like ajax(), load(), get(), and post(), and includes examples of GET and POST requests.
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/ 47

JavaScript Part IV:

Ajax/Fetch

Vyacheslav Koldovskyy
07/05/2018
Agenda
▪ Introduction to Ajax
▪ Using XMLHttpRequest object
▪ Ajax with jQuery
▪ Debugging AJAX Requests
▪ Live demo
▪ Links
Introduction to Ajax
What is Ajax?
▪ Ajax - acronym for Asynchronous JavaScript and XML
▪ Technically, Ajax is a set of web-development technologies
used on the client-side to create asynchronous web-
applications
▪ Web-applications with Ajax can send data to, and retrieve data
from, server asynchronously (in the background) without
interfering with the display and behavior of the existing page
▪ Ajax is widely used on modern web sites
Classic vs. Ajax Application
Communication Model
Same Origin Policy Limitation of Ajax
▪ Due to browser security restrictions, most Ajax
requests are subject to the same origin policy; the
request cannot successfully retrieve data from a
different domain, subdomain, port, or protocol.
▪ To overcome this restriction it is possible to use CORS
and JSONP
General Idea for XHR Usage
▪ XMLHttpRequest (XHR) object is the key to Ajax technology
▪ General idea of using XHR in Ajax:

2. Initialize XHR
properties with 3. Make 4. Handle
1. Create XHR
parameters of a request request result
request

▪ Note: Step 4 is asynchronous, this means that we don't suspend our code for
operation to complete, we pass callback function at step 2 and go further; it is
called when the request changes status or completes
Creating XMLHttpRequest object
▪ All modern browsers support the
XMLHttpRequest as native JS object. Syntax for
creating XHR as native JS object:

const xhr = new XMLHttpRequest();


Important Properties of XHR Object
• points to event handler that called each time
.onreadystatechange when property readyState changes

• holds current state of a request


.readyState • value equal to 4 means that request is done

• holds status of server response


.status • value 200 is OK

.responseText and • holds result of request in text or XML format


.responseXML
Important Methods of XHR Object
• prepares the request
.open() • sets request method, request URL and synchronous flag

• initiates the request


.send() • optional argument provides request entity body

• sets headers for the request


.setRequestHeader() • required for POST request

.abort() • aborts the request


Sample Usage of responseText for JSON
▪ In a sample below we assume that server returns encoded JSON data about client:
{ "name" : "John", "address": "Matrix Avenue" }
▪ We decode JSON data into JS object clientData and use its fields to fill some placeholders in
our page

01 var xhr = new XMLHttpRequest();


02 xhr.onreadystatechange = function () {
03 if (xhr.readyState === 4 && xhr.status === 200) {
04 var clientData = JSON.parse(xhr.responseText);
05 document.getElementById('clientName').innerHTML = clientData.name;
06 document.getElementById('clientAddress').innerHTML = clientData.address;
07 }
08 }
09 xhr.open('GET', 'user_data?id=1024', true);
10 xhr.send();
Event onreadystatechange
▪ Before sending request to a server we need to set a handler readyState:
for a special event – onreadystatechange 0 - UNSENT
▪ As Ajax request is asynchronous, the handler for the event
allows us to perform some actions based on the response 1 - OPENED

from a server
▪ The onreadystatechange event is triggered every time 2 – HEADERS_RECEIVED

the readyState changes


▪ The readyState numerical property holds the status of the 3 – LOADING

XMLHttpRequest: changing from 0 to 4, see picture on the


right 4 - DONE
Simple onreadystatechange Event Handler
01 xhr.onreadystatechange = function () {
02 if (xhr.readyState === 4 && xhr.status === 200) {
03 document.getElementById('someDiv').innerHTML = xhr.responseText;
04 }
05 }
Comments to the sample:
1. We create anonymous function and assign it to onreadystatechange property of XMLHTTPRequest object instance
2. As our function will be called each time the property readyState changes, we need to check when value becomes
equal to 4 (DONE state).
3. Also we have to check property status that returns status of the request. The value 200 means that result is OK, all
other values mean error.
4. In the body of handler we replace inner HTML contents of an element with someDiv id with contents of
responseText property
Sending Ajax Request
▪ To send a request to a server, we use the open() and send() methods of
the XMLHttpRequest object.
▪ Method open() specifies the type of request, the URL, and if the request
should be handled asynchronously or not: open(method,url,async)
– method: the type of request: GET or POST
– url: the address on the server to make request for
– async: true (asynchronous) or false (synchronous)
Note: as Ajax requests should be asynchronous, this value must be set to true
▪ Method send() sends the request off to the server: send(string)
– string: data to send, used for POST requests
GET Request
▪ Sample 'GET' request:
xhr.open('GET', 'ajax_page.aspx?name=John&value=42', true);
xhr.send();

▪ Comments:
– GET is simpler and faster than POST, and can be used in most cases
– Parameters should be transferred as part of URL address
– Maximum length of URL address limited, that is why it can't be used
for transferring volume data
– GET requests may be cached by browser
POST Request
▪ Sample 'POST' request:
xhr.open('POST', 'ajax_page.aspx', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('name=John&value=42');

▪ Comments:
– POST request is not limited in size, so it might be used for transferring volume data
– Parameters should be passed as argument for send() method
– Method setRequestHeader() should be used to define request headers for the
server to understand format of a request body
Server Response
▪ To get the response from a server, use one of
properties of the XMLHttpRequest object:
– responseText – get the response data as string, may be
used to transfer JSON data;
– responseXML – get the response data as XML data.
Sample Usage of responseXML
▪ In a sample below we assume that server returns some XML data about client:
<CLIENT>
<NAME>John</NAME>
<ADDRESS>Matrix Avenue</ADDRESS>
</CLIENT>
▪ We get XML data into JS object clientData of type XML Document and use it to fill some placeholders in our page
01 var xhr = getXHR();
02 xhr.onreadystatechange = function () {
03 if (xhr.readyState === 4 && xhr.status === 200) {
04 var clientData = xhr.responseXML;
05 document.getElementById('clientName').innerHTML =
06 clientData.getElementsByTagName('NAME')[0].childNodes[0].nodeValue;
07 document.getElementById('clientAddress').innerHTML =
08 clientData.getElementsByTagName('ADDRESS')[0].childNodes[0].nodeValue;
09 }
10 }
11 xhr.open('GET', 'user_data?id=1024', true);
12 xhr.send();
Demo 1: Ajax with Plain JavaScript
<!DOCTYPE html>
<html>
<head>
<script>
function getTextWithAjax() {
var xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById('target').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajax_info.txt', true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id='target'><h2>What is Ajax?</h2></div>
<button type='button' onclick='getTextWithAjax()'>Find out with Ajax</button>
</body>
</html>

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Fetch API
Fetch API Sample
fetch('/users.json’)
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
Fetch API Sample – POST
const form = document.querySelector('form’); fetch('/users', {
method: 'POST’,
fetch('/users', { headers: {
method: 'POST’, 'Content-Type': 'application/json’
body: new FormData(form) },
}) body: JSON.stringify({
name: 'Hubot’,
login: 'hubot’,
})
})
Ajax with jQuery
Methods of jQuery for Ajax Support
• main Ajax method of a jQuery library
.ajax() • provides numerous settings

• simplest Ajax method of a jQuery library


.load() • loads html code into some DOM element of a page

.get() • makes Ajax request by using HTTP GET method

.post() • makes Ajax request by using HTTP POST method

• loads JSON-encoded data from the server using HTTP GET request
.getJSON() • supports JSONP that allows to overcome same origin policy
Method .load()
▪ Method .load() loads html code into some DOM element of a page
▪ Syntax: .load( url [, data] [,complete] )
– url: string containing the URL to which the request is set
– data: plain object or string that is sent to the server
– complete: a callback function that is executes when the request completes
▪ Sample:
$('#result').load('ajax/test.html');

▪ Method supports jQuery selectors passed after url address that determine the
content to be loaded.
▪ Sample:
$('#new-projects').load('/resources/load.html #projects li');
Method .get()
▪ Method .get() loads data from the server using HTTP GET
request
▪ Syntax: .get( url [, data ] [, success ] [, dataType ] )
– url – a string containing the URL to which the request is sent
– data - a plain object or string that is sent to the server with the request
– success - a callback function that is executed if the request succeeds
– dataType - the type of data expected from the server. Default: Intelligent Guess (xml, json,
script, or html).

▪ Returns: method returns jqXHR object


Example of .get() Method Call
Sample usage of jQuery .get() method shown in an example below:
▪ we make GET request to some url 'example.php' passed as first argument assuming that it
returns json data with fields 'name' and 'address'
▪ as second argument we pass callback function that will add received data to the body of a
document
▪ as third argument we pass data format descriptor 'json'
▪ additionally we call .done() method of returned jqXHR object to log successful request

01 $.get('example.php', function(data) {
02 $('body')
03 .append('Name: ' + data.name)
04 .append('Address: ' + data.address);
05 }, 'json')
06 .done(function() {
07 console.log('Request completed successfully');
08 });
Method .post()
▪ Method .post() loads data from the server using HTTP POST
request. Syntax is identical to shown before method .get().
▪ Syntax: .post( url [, data ] [, success ] [, dataType ] )
– url – a string containing the URL to which the request is sent
– data - a plain object or string that is sent to the server with the request
– success - a callback function that is executed if the request succeeds
– dataType - the type of data expected from the server. Default: Intelligent Guess (xml, json,
script, or html).

▪ Returns: method returns jqXHR object


Method .getJSON()
▪ Method .getJSON() loads JSON-encoded data from the server using HTTP
GET request.
▪ Syntax: . getJSON( url [, data ] [, success ] )
– url – a string containing the URL to which the request is sent
– data - a plain object that is sent to the server with the request
– success - a callback function that is executed if the request succeeds

▪ Returns: method returns jqXHR object


▪ Important Note: If the URL includes the string 'callback=?' (or similar, as
defined by the server-side API), the request is treated as JSONP instead. This
allows to overcome same origin policy limitation of Ajax and make request to
other domains
Sample Sending Form

▪ https://jsfiddle.net/koldovsky/6pugnb57/1/
Debugging Ajax
Components of Ajax
Originally Ajax considered as based on the following
components:
– HTML (or XHTML) and CSS for presentation
– The Document Object Model (DOM) for dynamic display of and
interaction with data
– XML for the interchange of data, and XSLT for its manipulation
– The XMLHttpRequest (XHR) object for asynchronous communication
– JavaScript to bring these technologies together
Modern Ajax
▪ Modern paradigm of Ajax does not require all components
listed on the previous screen.
▪ For example, XML is not required for data interchange and,
therefore, XSLT is not required for the manipulation of data.
These components may be replaced by JSON (JavaScript
Object Notation).
▪ Also developers rarely use pure JavaScript code for Ajax
requests, it is far more convenient to use libraries like jQuery
or Prototype
Log XMLHttpRequest in Console
Breakpoints on XMLHttpRequest Events
To make breakpoints on XMLHttpRequest:
1. Click '+' button in XHR Breakpoints section;
2. Set URL filter in input field

1. Click button

2. Set URL filter


Network Tab Shows Ajax Requests
and Execution Time
Live Demo
Demo 2: Building Weather Service
<!DOCTYPE html>
<html>
<head>
<script src='//code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function() {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
});

function locationSuccess(position) {
var weatherAPI = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + position.coords.latitude +
'&lon=' + position.coords.longitude + '&callback=?';
$.getJSON(weatherAPI, function (response) {
$('#loc').html(response.city.name);
$('#temp').html(response.list[0].main.temp - 273.15);
});
}

function locationError(error) {
console.warn('Error:' + error.message);
}
</script>
</head>
<body>
<p>Location: <span id='loc'></span></p>
<p>Current temperature: <span id='temp'></span> &deg;C</p>
</body>
</html>
Useful links
Links
▪ XMLHttpRequest on W3C: http://www.w3.org/TR/XMLHttpRequest/
▪ Official jQuery Website: http://jquery.com/
▪ Ajax Tutorial on W3Schools.com http://www.w3schools.com/ajax/
Advanced
Creating XHR for All Browsers
To handle modern and old browsers we should check if the browser supports XHR object and
create an instance of it, if not, create an ActiveXObject:

01 function getXHR() {
02 var xhr;
03 if (window.XMLHttpRequest) {
04 // code for IE7+, Firefox, Chrome, Opera, Safari
05 xhr = new XMLHttpRequest();
06 } else {
07 // code for IE6, IE5
08 xhr = new ActiveXObject('Microsoft.XMLHTTP');
09 }
10 return xhr;
11 }
Method .ajax()
▪ Method .ajax() is the main Ajax method of jQuery library, it accepts:
1) one argument that is plain object with numerous fields containing all settings for method call
2) or two arguments: first is the url and second is the settings object
▪ Syntax:
1) .ajax( settings )
2) .ajax( url [, settings] )
▪ Returns: method returns jqXHR object, which is superset to XMLHTTPRequest and supports
additional methods that calls after request completes and may be linked to each other:
– .done(function( data, textStatus, jqXHR ) {});
– .fail(function( jqXHR, textStatus, errorThrown ) {});
– .always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
Object settings for jQuery.ajax
Some important fields of settings object passed as a parameter to .ajax() method:
▪ url – an address of the request
▪ data – transferred data (object or string)
▪ dataType – type of return data passed in callback function (xml, html, script, json, jsonp, text)
▪ type – request type (GET or POST)
▪ async – make asynchronous request (true by default)
▪ cache – enable data caching by browser (true by default)
▪ timeout – timeout of a request in milliseconds
▪ beforeSend – callback function to run before request sending
▪ error – callback function to run on error
▪ success – callback function to run on success result of a request
▪ complete – callback function to run when request completes
Example of .ajax() Method Call
In an example below we make POST request to some url 'getdata'; while making the
request we send contents of element with id 'dataForm' and set data type to html; in
case of success we convert request result into jQuery object, modify data by removing
last element of a list and append modified data to some element with id 'target'
01 $.ajax({
02 type: 'POST',
03 url: 'getdata',
04 data: $('#dataForm').serialize(),
05 dataType: 'html',
06 success: function (data) {
07 var jqObj = jQuery(data);
08 jqObj.find('li:last').remove();
09 $('#target').empty().append(jqObj);
10 }
11 });
How to Detect Ajax Request on Server Side?
▪ To detect if request from a client is an Ajax request we should
use HTTP_X_REQUESTED_WITH field on a server-side
▪ This field is set only when XMLHttpRequest object used to
make a request, it's natively supported by modern browsers
▪ Most server-side frameworks provide special property to check
for Ajax request that internally uses HTTP_X_REQUESTED_WITH
field
Thank you!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy