On Github andrei-yanovich / ajax-talk
Asynchronous JavaScript and XML
is a group of interrelated web development techniques used on the client-side to create asynchronous web applications.
The term Ajax was coined on 18 February 2005 by Jesse James Garrett in an article entitled "Ajax: A New Approach to Web Applications", based on techniques used on Google pages.
Ajax enables you to execute a server-side methods through a JavaScript call, whithout requiring a browser refresh.
JavaScript object.
Adopted by all browsers
Communicates with a server via standard HTTP GET, POST, PUT and DELETE
XMLHttpRequest object works in the background for performing asynchronous communication with the backend server
Response content type can be:
Properties:
Set with an JavaScript event handler that fires at each state change
current status of request
HTTP Status returned from server: 200 = OK
Properties:
String version of data returned from the server
XML document of data returned from the server
Status text returned from server
Methods:
open( method, URL, async, userName, password )
Modern standard events:
function initRequest() { // XDomainRequest for IE8, IE9 var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest; return new XHR(); };
function doCompletion(word, callback, errorback) { var url = "autocomplete?action=complete&id=" + escape(word); var req = initRequest(url); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { callback(JSON.parse(req.responseText)); } else { errorback(req.statusText); } } }; req.open("GET"/*type*/, url/*url*/, true/*async*/); req.send(null); };
function doCompletion(word, callback, errorback) { var url = "autocomplete"; var req = initRequest(url); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { callback(JSON.parse(req.responseText)); } else { errorback(req.statusText); } } }; req.open("POST"/*type*/, url/*url*/, true/*async*/); req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') req.send("action=complete&id=" + escape(word)); };
$.ajax({ type: 'POST', url: 'echo', data: { testingMethod: 'Get' }, success: function(resp) { var responseContainer = document.querySelector(".response"); responseContainer.innerText = JSON.stringify(resp); } });api.jquery.com/category/ajax/
jQuery Ajax shorthands:
Load data from the server using a HTTP GET request
$.get( "test.php", { name: "John", time: "2pm" } ) .done(function( data ) { alert( "Data Loaded: " + data ); }); });
Load data from the server using a HTTP POST request.
$.post( "ajax/test.html", function( data ) { $( ".result" ).html( data ); });
Load data from the server and place the returned HTML into the matched element.
$( "#result" ).load( "ajax/test.html #container" );
jQuery Ajax shorthands:
Load JSON-encoded data from the server using a GET HTTP request.
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; $.getJSON( flickerAPI, { tags: "mount rainier", tagmode: "any", format: "json" }) .done(function( data ) { $.each( data.items, function( i, item ) { $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" ); if ( i === 3 ) { return false; } }); });
Load JSON-encoded data from the server using a GET HTTP request.
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { console.log( data ); // Data returned console.log( textStatus ); // Success console.log( jqxhr.status ); // 200 console.log( "Load was performed." ); });
The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's DOM with no specific restrictions, but prevents access to DOM on different sites.
Same-origin policy also applies to XMLHttpRequest and to robots.txt.
Read more"http://www.example.com/dir/page.html"
JSON with padding
is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.
// Object to fetch { "Name": "Foo", "Id": 1234, "Rank": 7 }
<!-- server2.example.com --> <script src="http://server2.example.com/Users/1234?jsonp=parseResponse"> </script>
// Response with padding parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
Cross-origin resource sharing.
is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from.
HTTP access control (CORS)February 25, 2008: XMLHttpRequest 2.0 W3C working draft
Request
(Access-Control-Allow-Origin: *)
Response
IE8 and IE9
Only GET and POST
Request headers:
Indicates the origin of the cross-site access request or preflight request.
Used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made.
Used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made.
Simple Request
Response headers:
The origin parameter specifies a URI that may access the resource.
Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request.
Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.
This header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.
Request with credentials
var invocation = new XMLHttpRequest(); var url = 'http://bar.other/resources/credentialed-content/'; function callOtherDomain(){ if(invocation) { invocation.open('GET', url, true); invocation.withCredentials = true; invocation.onreadystatechange = handler; invocation.send(); } }
GET /resources/access-control-with-credentials/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: http://foo.example/examples/credential.html Origin: http://foo.example Cookie: pageAccess=2
HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:34:52 GMT Server: Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.61 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2 X-Powered-By: PHP/5.2.6 Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Credentials: true Cache-Control: no-cache Pragma: no-cache Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 106 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain [text/plain payload]
Push, or server push, describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. It is contrasted with pull, where the request for the transmission of information is initiated by the receiver or client.
Techniques:
Frequent requests for notifications to the server
The same as polls but the connection stays open until it gets a new notification
Iframe with opened connection which is updated by the server with script tags