What is AJAX? To find out, read the first two paragraphs of MDN’s AJAX page.
Fundamental to AJAX is the XMLHttpRequest object (a.k.a. XHR) for sending HTTP requests.
An XHR provides an easy way to retrieve data from a URL without having to do a full page refresh. You simply create an instance of the object, open a URL, and send the request.
AJAX is so successful because the developer can:
- Update a web page without reloading the page
- Request data from a server – after the page has loaded
- Receive data from a server – after the page has loaded
- Send data to a server – in the background
Testing AJAX Apps
AJAX apps must be run on an HTTP server and, in general, cannot be tested by using Atom’s Open in Browser command (the file:// protocol won’t work).
Therefore, you will create a testing server on your computer using Node.js and Express.
AJAX With/Without jQuery
jQuery adds a higher-level API for AJAX requests, thus hiding the details of the XMLHttpRequest object.
- $.getJSON() is a jQuery shorthand function for JSON requests only
- jQuery’s $.ajax() function can be used for JSON requests, plus more
- jQuery AJAX examples
JavaScript’s Fetch API is a modern alternative that is replacing jQuery and XMLHttpRequests.
We will use both jQuery and fetch.
Getting Images from Flickr
A Web API is a web-based method for computer systems to exchange data.
The photo-sharing service Flickr, for example, offers an open API (no developer key needed) to retrieve photos:
Open your web browser and type in the following URL:
http://api.flickr.com/services/feeds/photos_public.gne?tags=dogs&format=json
- Open the URL in Chrome to see the JSON data returned by the API.
- Open it in Chrome’s Postman app to see the JSON data in a much clearer way.
AJAX Security
The Same-Origin Policy is an important concept in the Web Application Security Model. Browsers restrict cross-origin HTTP requests for data in a <script> tag:
<script type="application/javascript" src="http://server.example.com/Users/1234"><script>
The request URL must be from the same domain the application was loaded from (unless special request headers are used).