Introduction to jQuery_5

Module 3.2.

Before Start

The following contents are the notes I took when learning jQuery on Edx.

Mainly for front-End Web developers, check here to get more details.

CONTENTS

Three parts:

Module3 : Asynchronous programming and Ajax

Module3 includes five parts:

  • Using promises
  • Web workers
  • Using deferred
  • JavaScript Object Notation
  • Calling the server

Let’s get to know something about JSON and Ajax.

  • JavaScript Object Notation

    • JSON syntax

      A JSON object uses a notation that’s similar to that of a JavaScript object.

      Example:

      //create a JavaScript object
      var person = {
          firstName: 'Christopher',
          lastName: 'Harrison'
      }
      
      //create a JSON object
      var person = {
          'firstName': 'Christopher',
          'lastName': 'Harrison'
      }
      

      Create a more complex object:

      var person = {
          'firstName': 'Christopher',
          'lastName': 'Harrison',
          'email': {
              'address': '[email protected]',
              'type': 'business'
          }    
      }
      

      Create a object with array:

      var person = {
          'firstName': 'Christopher',
          'lastName': 'Harrison',
          'emailAddresses': [
              {
                  'address': '[email protected]',
                  'type': 'business'
              },
              {
                  'address': '[email protected]',
                  'type': 'home'
              }
          ]
      }
      
    • Serializing objects

      JavaScript provides a native utility for converting objects to JSON (serializing), and converting JSON strings to objects (deserializing).

      • Serializing an object: JSON.stringify

        // Create an instance of Object, a basic JavaScript object
        var person = new Object();
        
        // add properties
        person.firstName = 'Christopher';
        person.lastName = 'Harrison';
        
        // serialize
        var jsonString = JSON.stringify(person);
        
      • Deserializing JSON: JSON.parse

        // Deserialize a JSON string
        var newPerson = JSON.parse(jsonString);
        
        // access properties as normal
        $('#first-name-display').text(newPerson.firstName);
        $('#last-name-display').text(newPerson.lastName);
        
  • Calling the server

    • Introducing Ajax

      Typically, when we make a call to the server, we need to refresh the entire page.

      as developers, we’d like to be able to incorporate server-side resources into our pages, allowing us to update individual portions of the page with new data, rather than updating the entire page.

      • Asynchronous JavaScript and XML (Ajax)

        Ajax is a set of technologies that act together to make it easier for developers to make calls to server resources from JavaScript.

      • Basic data retrieval

        get : The most basic Ajax operation we can perform using jQuery.

        get contacts the URL we provide, and passes the string the server returns into the parameter we’ll use for our event handler.

        Example:

        $.get(
            'some-url', // The URL to call
            function(data) { // Success event handler
                // The data parameter contains the string
                $('#output').text(data);
            }
        );
        
      • jQuery Ajax and promises

        All jQuery Ajax calls return a jQuery promise.

        So, you can use done for your success event handler, and fail to catch any errors. The two code samples perform the same operations.

        Example:

        // Option one (pass the success function as a parameter)
        $.get('some-url', function(data) { $('#output').text(data); });
        
        // Option two (use the done function of the promise)
        $.get('some-url').done(function(data) { $('#output').text(data); });
        
    • Retrieving JSON objects

      • getJSON

        To retrieve a JSON object, you can use getJSON.

        getJSON accepts several parameters, but the most common two that you’ll provide are the URL you need to call, and an event handler for success.

        Because getJSON is expecting JSON data, it automatically deserializes the object, meaning you do not need to call JSON.parse.

        Example:

        $.getJSON('/api/Demo', function (person) {
            $('#first-name').val(person.firstName);
            $('#last-name').val(person.lastName);
        });
        
    • Making server calls

      If you’re new to making server calls through JavaScript or other technologies, you might have a few questions about how you’re supposed to know where the data is, what URLs you should use, etc.

      • Finding the right URL

        Most commonly you’ll be calling your own server and accessing your own organization’s data.

        Then the answer becomes even easier:

        talk to the developer who created the server side code that you need to call. They can provide all of the information you need.

      • Verbs

        HTTP offers several “verbs”, with the two most common being GET and POST.

        GET and POST in HTTP terms are about how to send data to the server, not a determination of the server sending you data.

        GET limits us to sending data in the URL only.

        POST on the other hand allows us to send data both in the URL, but also in what’s known as the header.The header is information that’s sent behind the scenes from the client to the server, and can be used to send almost any type of data, including binary data.

      • HTTP and REST APIs

        HTTP provides several verbs, including GET, POST, PUT and DELETE.

        GET will retrieve objects,

        POST will create a new object,

        PUT will update an existing object,

        DELETE will delete an object.

        Building upon those common operations, the W3C has established a specification called REST. REST provides for various standards to provide even more consistency when making server calls.

    • Posting data

      If the service you’re using follows standard REST practices, you’ll notice that you can create a new object by calling POST.

      Or, if you’re trying to upload a binary object, such as an image, you’re forced to use POST, as GET won’t allow that type of data to be uploaded.

      • post

        Like getJSON, it also passes the JSON object returned by the server into the parameter for the event handler. And, just like all of the Ajax calls we’ve seen, post also returns a promise.

        Example:

        // get the data we need to send
        var person = { firstName: 'Christopher', lastName: 'Harrison' };
        
        // Call POST
        
        $.post('URL', // Pass in the URL you need to access
            person, // Pass in the data to send via POST
            function(data) {
                // success event handler
                // parameter contains value returned by server
            }
        );
        
    • Ajax events

      • Start events

        The two starting events are ajaxStart and ajaxSend.

        ajaxStart is raised when the first Ajax call is being made.

        ajaxSend is raised each time an Ajax call is made.

      • Completion events

        jQuery Ajax offers two main events when each Ajax call is finished, ajaxSuccess, which is raised when a call succeeds,

        ajaxError, which is raised when a call fails.

        ajaxComplete is raised when each Ajax call completes, regardless of success or failure.

        ajaxStop is raised when all calls are completed.

        Example:

        $(document).ajaxSend(function () {
            // raised when a call starts
            $('#status').append('<div>Call started</div>');
        }).ajaxComplete(function () {
            // raised when a call completes
            $('#status').append('<div>Call completed</div>');
        });
        
    • Dynamically loading data

      • Loading HTML

        load will call the URL provided, obtain the HTML, and place it in the targeted item.

        $('#target').load('some-url.html');
        
      • Loading and executing JavaScript

        getScript downloads and executes the script when it’s called.

        $.getScript('some-url.js');
        

This is Module3 all about. More details.