AJAX: Asynchronous JavaScript and XML
AJAX stands for Asynchronous JavaScript and XML. AJAX is a way to exchange data with a server using JavaScript; this allows updating parts of a web page instead of reloading a whole new page. Example applications using AJAX includes Google Maps, Gmail, Google Docs.
History
In 1999, XMLHttpRequest was introduced in IE and other browsers. In 2005, Jesse James Garrett coined the term “AJAX” to describe how the following technologies are incorporated using JavaScript.
- HTML and CSS for the structure and presentation
- The Document Object Model (DOM) for dynamic changes
- XML (and JSON) for the data exchange
- The XMLHttpRequest object for asynchronous communication
XMLHttpRequest
JavaScript uses the XMLHttpRequest object to communicate with a server. XMLHttpRequest is a web standard by W3C. It has the following methods and properties.
- open(method, url, async): specifies the request details: method (GET or POST), url,
async (true or false). - send(string): sends the request. The parameter “string” is only used for POST requests.
- onreadystatechange: a callback function to be called whenever “readyState” changes.
- readyState: Possible values: 0 (not initialized), 1 (connection established), 2 (request received), 3 (request in the process), 4 (request finished and response is ready)
- status: the response status: 200 (OK), 404 (Page not found)
- responseText: the response data as a string
The following code shows how to use XMLHttpRequest. Note that “onreadystatechange” is a callback function.
var url = '...'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState != 4 || xmlhttp.status != 200) return; var data = xmlhttp.responseText; // process data } xmlhttp.open("GET", url, true); xmlhttp.send();
A complete demo is in the link below. It loads a JSON file and updates the page.
http://theoryapp.com/my/web/ajax-demo.html
AJAX using jQuery
The jQuery library simplifies the AJAX coding. It has a method “ajax” which handles the request-response process. The following code is a simple example.
var url = '......'; jQuery.ajax({ url: url, dataType: 'json', async: true, success: function(data, status, xhr) { // data is parsed as JSON // process data } });
Note that, “dataType” allows specifying the data format of the response; “success” is a callback function to be run when the request is completed successfully.
A complete demo using jQuery AJAX is in the link below. It loads a JSON file and updates the page.
http://theoryapp.com/my/web/ajax-demo-jquery.html
Example: Search Tweets using AJAX
Twitter provides APIs for searching tweets. The following code shows how to use AJAX to search for tweets. The HTML part creates a search box and a button. The JavaScript code does the following:
- Attach a event listener
- When “click” happens, send an AJAX request
- When the request finishes, display on the page
<input type="text" name="query" id="query"> <input type="submit" value="Search" id="search"> <div id="result"></div> <script type="text/javascript"> jQuery('#search').click(function() { var query = jQuery('#query').val() || 'twitter'; fetchTweets(query); }); function showTweets(data) { jQuery('#result').empty(); for (var i in data['results']) { var status = data['results'][i]; var id = status.id_str; var html = '<p>' + status.text + '<br/>' + '<a href="https://twitter.com/' + status.from_user + '/status/' + id + '">' + 'By ' + status.from_user + '</a>' + '</p>'; jQuery('#result').append(html); } } function fetchTweets(query) { var url = 'http://search.twitter.com/search.json'; var parameter = { q: query }; jQuery.ajax({ url: url, data: parameter, crossDomain: true, dataType: 'jsonp', success: showTweets }); } </script>
Note that this uses cross domain request. The complete code is the following link: http://www.theoryapp.com/my/web/ajax-tweet.html.
References
- Wikipedia: Ajax
- Wikipedia: XMLHttpRequest
- Jesse James Garrett (2005). “Ajax: A New Approach to Web Applications”
- jQuery: jQuery.ajax()