Tuesday, May 23, 2017

Ajax Lesson

NOTE: This lesson uses jQuery as the interface for basic AJAX work. By no means is AJAX a product of jQuery and you do not need jQuery to utilize AJAX.

What Is Ajax

In 1999 Microsoft created a new update for IE5 that would dynamically update stories on particular Microsoft webpages. This technology was later adopted by the rest of the Browser collective. Jesse James Garrett, in 2005, coined the term AJAX which stood for Asycronous JavaScript And Xml. A year later it received its first W3C draft specification.
AJAX allowed webpages to continually request resources without the need to reload the entire webpage. This allowed users to stay on a webpage longer and interact with other various features of that page as the requests were made. The asynchronicity that this brought revolutionized the previous web era, where all dynamic changes required a complete trip to the server for a full refresh of the page with the new content based on the user's intent.

Using Ajax

Utilizing AJAX can be complicated even today as some versions of IE and other browsers still have a different mechanism to initiate the calls. Therefore it is recommended to use a library or application framework which comes with an AJAX service to make these requests.

Getting Started

We will need to install jQuery and place it in our HTML page so that we can then write some code to make this all come together.

bower install jquery --save

index.html


    
        Hello World
    

    

Hello World!

  • No Items in data

js/app.TS

$('#data')
    .on('click', function(event: JQueryEventObject){
        $.ajax({
            accepts: 'text/json',
            method: 'Get',
            url: 'data/words.json'
        })
        .done(function(data){
            let words = data;
            let $elm = $('#result');

            // Clear html content
            $elm.html('');

            words.forEach(function(word){
                $elm.append(`
  • ${word}
  • `); }); }); });

    The path for the Url is to a resource file containing an array of strings. This could easily be a service in NodeJS or WebAPI. It could be a Twitter feed that you are pulling, though you would need some additional parameters to get it working.
    The simplicity of AJAX allows for many online experiences that we take for granted today. Real-time web applications take full advantage of the power of AJAX.

    No comments: