AJAX

From BC$ MobileTV Wiki
Jump to: navigation, search

Asyncronous Javascript And Xml Asynchronous JavaScript and XML (commonly abbreviated AJAX) is emerging as one of the most effective methods of creating interactive Web Applications. It is a method which combines client-side script (typically JavaScript, JScript or VBscript) and server-side data or computation, along with some RIA techniques (such as DHTML, Drag & Drop and Animation) for improving the usability and interactivity of Web Applications. [1]


Specifications

Standards

AJAX is based on 4 existing web standards which are well defined and supported by all major browsers:

  1. JavaScript
  2. XML
  3. HTML
  4. CSS

[2]

AJAX Client-Server



AJAX

Advantages of AJAX include:

* Don't need to reload the whole page to send or get updated data
* Added interactivity and responsiveness can be acheived
* Works with ANY server-side language

[3]


Disadvantages of AJAX are:

* Doesn't work if JavaScript is disabled
* Asynchronous nature can cause data contention or race problems when updating data

[4]


Domain processing

URL parameters

[5] [6] [7] [8]


Hash/Anchor


XHR

XMLHttpRequest (commonly abbreviated XHR) is a standard mechanism for creating requests to server-side components of an application (typically for passing or requesting data dynamically, in an AJAX-type call).

Firefox/Netscape/Opera/Safari/Chrome

http_request = new XMLHttpRequest();
AJAX HTTP Request

ActiveX Object

IE 5/6

http_request = new ActiveXObject("Microsoft.XMLHTTP");

IE 7/8

http_request = new ActiveXObject("Msxml2.XMLHTTP");


AJAX Multi-user Session


Requests

GET

http_request.open('GET', 'data.xml');

POST

http_request.open('POST', 'data.xml', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(parameters);

PUT

http_request.open('POST', 'data.xml');
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader('X_METHODOVERRIDE', 'PUT');

DELETE

http_request.open('POST', 'data.xml');
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader('X_METHODOVERRIDE', 'DELETE');

[9] [10]


Headers

Given the XHR instantiation above, you can set the request header using the following (after initializing the XMLHttpRequest object):

xhr.setRequestHeader('User-Agent', 'BC$');

You can also access the response Header as follows:

xhr.getResponseHeader('User-Agent');

[11] [12] [13] [14] [15] [16] [17]

Response Handler

The following code handles changes in state as a result of a request (i.e. response returned, errors, redirects, etc):

http_request.onreadystatechange=function(){
//ready to read response data
if (mypostrequest.readyState==4) {
 //200 = HTTP status code for 'Successfully completed request'
 if (mypostrequest.status==200){
  document.getElementById("result").innerHTML = http_request.responseText; //simply write raw text from response, in this example
 }
 else{
  alert("ERROR: Could not make request")
 }
}

}


Callbacks

A callback is a function which is called from a reference. It is useful for delaying processing of a method.

For example, to set a time to wait before running the function:

setTimeout(callback, TIME) 

where TIME is a millisecond representation like 1000 for 1 second.

For processing results of an XML HTTP Request (XHR) when they are ready

http_request.onreadystatechange = callback 

Complete AJAX XHR callback example:

<html>
<head>
<script type="text/javascript">
function myFunction()
{
    loadXMLDoc("ajax_info.txt",alertResponse); //can call alertResponse or showResponse or any other new method as a "callback"
}
function loadXMLDoc(url,_cfunc)
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else 
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=(typeof _cfunc != "undefined") ? _cfunc : showResponse;
  xmlhttp.open("GET",url,true);
  xmlhttp.send();
}
function showResponse()
{
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
}
function alertResponse()
{
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
     alert(xmlhttp.responseText);
   }
}
</script>
</head>
<body>
 < div id="myDiv">Let AJAX change this text</div >
 <button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>

[18]


Promise

"A promise object represents a value that may not be available yet. The primary method for interacting with a promise is its then method."[19]

[27] [28] [29] [30] [31] [32] [33] [34] [35] [36]


Fetch

[39]


Async-Await

[40] [41] [42] [43]

WebWorkers

WebWorkers are like AJAX requests that run completely in the background on a separate thread outside of the main render/blocking thread of the browser instance. They are useful for any AJAX-like data fetching operations that take longer to process (and could even be beneficial in areas that simply have a chance of taking longer).

See also: HTML5 WebWorkers


Service Workers

Service Workers are a technology to help Proxy (intercept) all incoming and outgoing requests, modify it, return something immediately, or decide based on a caching policy whether or not it should try to fetch a response from the server.

 if ('serviceWorker' in navigator) {
   navigator.serviceWorker.register('service-worker.js')
   .then(() => console.log('ServiceWorker installed'))
   .catch(err => console.log('Error: ', err));
 }

 self.addEventListener('activate', (event) => {
   event.waitUntil(
     caches
       .open('my-sw-cache')
       .then(function(cache) {
          return cache.addAll([
            'main.js',
            'main.css'
          ]);
       })
       .then(function(){
          console.log('ServiceWorker ready, assets cached');
       })
   );
 });

See also: HTML5 Service Workers

Beacons


Same Origin Policy

The Same Origin Policy (also known as the Same Domain Policy) dates back to the days of Netscape and limits the sending of requests, data, objects or documents through JavaScript across separate domains, protocols, or port numbers.


[46]

AJAX Proxy

Server-side Proxy


CORS

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries.

On the server-side, it is relatively straightforward to add support for CORS, requiring only the addition of a Header to the hosting server. The following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

Header set Access-Control-Allow-Origin "*"

When sent in a request/response header, it would look like the following:

Access-Control-Allow-Origin: *

-or-

Access-Control-Allow-Origin: http://sometrustedsite.com

One limitation of this new security mechanism is the inability to represent multiple domains, as such, you must either allow all sites to pull data from your APIs or pages (as per the example above), or, only respond back that you do or don't specific single site. The only way to "whitelist" multiple domains is to handle this on the server-side, perform a lookup and list that single allowed domain, for instance in Apache Web Server you could add the required header dynamically this way:

# ------------------------------------------------------------------------------
# Allow loading JavaScript, JSON, XML or CSS files to a list of trusted partners
# ------------------------------------------------------------------------------
<FilesMatch "\.(js|json|xml|css)$">
   <IfModule mod_headers.c>
       SetEnvIf Origin "http(s)?://(www\.)?(trustedsite1.com|trustedsite1.net|trustedsite2.ca|dev.trustedsite3.tv)$" AccessControlAllowOrigin=$0
       Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
   </IfModule>
</FilesMatch>

[47] [48] [49]

On the client-side, XMLHTTPRequest2 supports a new withCredentials property that is required to be set to enable a CORS request to go out to a CORS-compliant/configured server. In IE which lacks XHR2, you can instead use XDomainRequest method. For simplicity, you could use the following function[50]:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
   // Check if the XMLHttpRequest object has a "withCredentials" property, which only exists on XMLHTTPRequest2 objects
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
   // Otherwise, check for XDomainRequest, which exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
   // Otherwise, CORS is not supported by the browser.
    xhr = null;
  }
  return xhr;
}

[55] [56] [57] [58] [59] [60] [61] [62] [63] [64]

[65]


CORP

[66]

CORB


COOP


COEP

Cross-Origin Embedder Policy (COEP): https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy


Reverse AJAX

AJAX works by allowing us to fetch new content or data on demand, or at a set interval, as desired. However, sometimes we want data to flow in the other direction (from origin server towards our active/running application). In these cases, we can use a "Reverse AJAX" technique to push data from remote servers into our Web Application.

To realize Reverse AJAX, there are a few alternatives:

  1. HTML5 WebSockets (persistent connections with a server and Server-Sent Events for receiving messages as push notifications that can be processed in the DOM using JavaScript)
  2. Applet sockets (a predecessor of the emerging WebSockets standard, early Applets were the first to enable real-time communication using a dedicated TCP socket connection between client and server, that was only closed when the user closed the Applet or page it was embedded in)
  3. Slow-load (also called "Long-polling", uses keep-alive Connection and lengthy server-side maximum execution times to "wait" for new incoming data)
  4. Polling (simulates a real-time push connection by periodically checking on a set interval, with a small enough interval the data arrives in near-realtime)
  5. HTTP Streaming (also called long-lived HTTP, keeps connection alive between client and server even after data is delivered, until expiration timestamp is passed)
  6. Comet (aka long-held HTTP, once client requests an endpoint, the server returns the data as slowly as possible, trying to maintain an open connection for as long as possible, using "no timeouts")
  7. Piggyback (aka "store and forward", new data arrives at the server and gets stored, the client makes an unrelated request and the Reverse AJAX data gets appended on top of the unrelated response, usually with some form of divider or header to identify where the unrelated data starts and ends)
  8. META refresh in hidden iFrame (aka poor-man's Reverse AJAX, simply refresh the page on a set interval so it can be updated, then the contents of the iFrame can be grabbed... refreshing the iFrame too often can affect server load times)

[67] [68] [69] [70] [71]

Pushlets

DWR

Comet

Kaazing

APE

JMS

Libraries

See: JavaScript



COMET

LightStreamer


AHAH


Orbited

Orbited provides a pure JavaScript/HTML socket in the browser. It is a web router and firewall that allows you to integrate web applications with arbitrary back-end systems. You can implement any network protocol in the browser—without resorting to plugins.



Tools


Open Source (Free)

Open Source (Commercial)

Closed Source (Free)

Closed Source (Commercial)


Resources


Tutorials

[73]

[74]


[80]


External Links


References

  1. For more info check out the wikipedia page on AJAX: wikipedia:AJAX
  2. AJAX -- Introduction and Advantage: http://ajaxblog.com/archives/2009/01/25/ajax-introduction-and-advantage
  3. Why use AJAX?: http://www.interaktonline.com/support/articles/Details/AJAX:+Asynchronously+Moving+Forward-Why+use+AJAX%3F.html?id_art=36&id_asc=309
  4. Troubles with Asynchronous Ajax Requests and PHP Sessions: http://www.chipmunkninja.com/Troubles-with-Asynchronous-Ajax-Requests-g@
  5. Javascript function to get URL query string parameters: https://snipplr.com/view/13239/javascript-function-to-get-url-query-string-parameters
  6. Get URL Parameters with JavaScript: https://html-online.com/articles/get-url-parameters-javascript/
  7. How to Get URL Query Parameters with Javascript (process with for each): https://usefulangle.com/post/78/javascript-get-url-parameters
  8. How to get URL parameter using jQuery or plain JavaScript?: https://stackoverflow.com/questions/19491336/how-to-get-url-parameter-using-jquery-or-plain-javascript
  9. An absolute Guide to JavaScript Http Requests (XHR .vs. Fetch .vs. Axios lib): https://medium.com/javascript-in-plain-english/an-absolute-guide-to-javascript-http-requests-44c685edfa51
  10. Why JavaScript Developers Should Prefer Axios Over Fetch: https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c
  11. The XMLHttpRequest Object: http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/#dfn-setrequestheader
  12. Understanding User-Agent Strings: http://msdn.microsoft.com/en-us/library/ms537503(v=VS.85).aspx
  13. Accessing the web page's HTTP Headers in JavaScript: https://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript
  14. How to read/get response header from AJAX/HTTP/Service/API call or response: https://medium.com/@jsguyhenry/how-to-read-get-response-header-from-ajax-http-service-api-call-or-response-c873c5fbf9b8
  15. jQuery - get AJAX response headers: https://stackoverflow.com/questions/11440918/jquery-get-ajax-response-headers
  16. jQuery and AJAX response header: https://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header
  17. jQuery & AJAX response header: https://cmsdk.com/node-js/jquery-and-ajax-response-header.html
  18. Try this Editor: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
  19. Mozilla Dev - Javascript Promises: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
  20. Promise/A+ spec on GitHub: https://github.com/promises-aplus/promises-spec/blob/1.0.0/README.md
  21. Q - the asynch JS Promise library: http://documentup.com/kriskowal/q/ SRC | DOCS | EXAMPLES
  22. Q - httpReadRetry example: https://gist.github.com/kriskowal/593052
  23. BluebirdJS: http://bluebirdjs.com/docs/getting-started.html | SRC (Promise polyfill lib)
  24. Native Promise ONLY: https://github.com/getify/native-promise-only
  25. A small embeddable Promise polyfill: https://github.com/bramstein/promis
  26. Lightweight ES6/A+ compliant Promise Polyfill: https://github.com/taylorhakes/promise-polyfill
  27. MozDev -- Promise API: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  28. JavaScript Promise API: https://davidwalsh.name/promises
  29. Aren't promises just callbacks?: https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks/22562045#22562045
  30. What is the "explicit Promise construction" antipattern and how do I avoid it?: https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it
  31. Function that retries with setTimeout: https://stackoverflow.com/questions/31922159/javascript-function-that-retries-with-settimeout
  32. Promise Retry Design Patterns: https://stackoverflow.com/questions/38213668/promise-retry-design-patterns/44577075#44577075
  33. Promises -- Repeat operation until it succeeds?: https://stackoverflow.com/questions/26694467/promises-repeat-operation-until-it-succeeds#26694802
  34. Promises and setTimeout: https://stackoverflow.com/questions/42771837/promises-and-settimeout#42774486
  35. Wrapping jQuery AJAX requests with simple Promises: https://codepen.io/aevanson/pen/mGVNaR
  36. Promises in "vanilla JS": https://medium.com/@vikingjonsson/promises-in-vanilla-js-10588e629abb
  37. Fetch API: https://davidwalsh.name/fetch
  38. Introduction to the Fetch API: https://www.sitepoint.com/introduction-to-the-fetch-api/
  39. Using Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  40. Async Await JavaScript Tutorial – How to Wait for a Function to Finish in JS: https://www.freecodecamp.org/news/async-await-javascript-tutorial/
  41. How To Use Async and Await In JavaScript: https://www.js-tutorials.com/javascript-tutorial/how-to-use-async-and-await-in-javascript/
  42. NodeJS -- Modern Asynchronous JavaScript with Async and Await: https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await
  43. How To Master Async/Await With This Real World Example: https://medium.com/free-code-camp/how-to-master-async-await-with-this-real-world-example-19107e7558ad (real-time currency converter example)
  44. Beacon spec (LATEST): https://w3c.github.io/beacon/
  45. Beacon API: https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
  46. Understanding Web Security Checks in Firefox (Part 1): https://blog.mozilla.org/attack-and-defense/2020/06/10/understanding-web-security-checks-in-firefox-part-1/
  47. Access-Control-Allow-Origin M+ultiple Origin Domains?: https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains
  48. Setting CORS (cross-origin resource sharing) on Apache with correct response headers allowing everything through: https://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/
  49. Vary -- origin response header and CORS exploitation: https://security.stackexchange.com/questions/151590/vary-origin-response-header-and-cors-exploitation#151596
  50. Using CORS: http://www.html5rocks.com/en/tutorials/cors/
  51. wikipedia: Cross-origin resource sharing
  52. Browser Support Table - CORS: http://caniuse.com/cors
  53. CORS-Compliant REST API with Jersey and ContainerResponseFilter: http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/
  54. CORS-enable Tomcat - Why REST with JSONP when you can CORS?: http://sunnytalkstech.blogspot.ca/2012/01/why-rest-with-jsonp-when-you-can-cors.html (Tomcat)
  55. Cookies With My CORS: https://quickleft.com/blog/cookies-with-my-cors/
  56. Cross-site XMLHttpRequest with CORS: https://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
  57. Putting it all together – CORS tutorial for IIS: https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/
  58. Understanding CORS (in Spring): https://spring.io/understanding/CORS
  59. Understanding and using CORS (in RESTlet): http://restlet.com/company/blog/2015/12/15/understanding-and-using-cors/
  60. Making Cross-Domain Requests with CORS: https://www.eriwen.com/javascript/how-to-cors/
  61. How to use CORS to access Google APIs: https://developers.google.com/api-client-library/javascript/features/cors
  62. HTML5 - CORS: https://www.tutorialspoint.com/html5/html5_cors.htm
  63. CORS request - why are the cookies not sent?: https://stackoverflow.com/questions/8863571/cors-request-why-are-the-cookies-not-sent#8870830
  64. Basics of CORS (Cross-Origin Resource Sharing): https://dzone.com/articles/basics-of-cors
  65. Mozilla Dev docs -- Is Access-Control-Allow-Origin: * insecure?: https://advancedweb.hu/2019/11/12/cors_star/
  66. Safely reviving shared memory (with evolving W3C recommended COOP & CORE HTTP headers): https://hacks.mozilla.org/2020/07/safely-reviving-shared-memory/
  67. wikipedia: Reverse Ajax
  68. The Slow Load Technique/Reverse AJAX - Simulating Server Push in a Standard Web Browser: http://www.obviously.com/tech_tips/slow_load_technique
  69. Using Server Push (aka Reverse AJAX): http://biese.wordpress.com/2009/03/03/using-server-push-aka-reverse-ajax/
  70. Exploring Reverse AJAX: http://gmapsdotnetcontrol.blogspot.com/2006/08/exploring-reverse-ajax-ajax.html
  71. Google -- Polling Like It's the 90s: https://dzone.com/articles/google-polling-like-its-the-90s ( technical review of the live score feature in Google search results)
  72. Building an iOS photo feed with Pusher and Raspberry Pi: https://blog.pusher.com/building-ios-photo-feed-pusher-raspberry-pi/
  73. Inject a script tag with remote src and wait for it to execute: https://stackoverflow.com/questions/8578617/inject-a-script-tag-with-remote-src-and-wait-for-it-to-execute
  74. Understanding the Async JS event loop: https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff
  75. Element innerText/textContent for all browsers: http://perrymitchell.net/article/element-innertext-textcontent-for-all-browsers/
  76. 'innerText' works in IE, but not in Firefox: https://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox/1359822#1359822
  77. innerText vs innerHtml vs label vs text vs textContent vs outerText: https://stackoverflow.com/questions/24427621/innertext-vs-innerhtml-vs-label-vs-text-vs-textcontent-vs-outertext
  78. innerText vs. textContent: https://kellegous.com/j/2013/02/27/innertext-vs-textcontent/
  79. The poor, misunderstood innerText: http://perfectionkills.com/the-poor-misunderstood-innerText/
  80. What is callback hell?: https://www.quora.com/What-is-callback-hell?share=1

See Also

JavaScript | XML | JSON | jQuery | HTML5 | xHTML | HTML | DHTML | Drag & Drop | CORS | JSP | C#