Richland College Multimedia Learning Center

JavaScript, jQuery, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 8/15/2020 at 1:55pm

jQuery and AJAX


References


Introduction

AJAX (Asynchronous JavaScript and XML) is a method of building pages for the Web that process user requests immediately. What this means is that you can use AJAX to change a small part of the page in response to something that the user does, instead of reloading the entire page.

AJAX combines several programming tools including:

All of the major browsers now support the XMLHttpRequest object, so AJAX is gaining in popularity and wider usage on Web sites.

And now that jQuery is becoming more popular among Web developers and the companies that hire them, jQuery is becoming one of the most common means of adding AJAX processing to your pages. jQuery includes a lot of handy functions and selectors to make AJAX fairly easy to implement.


The PHP Pages

For this e-handout, we will be using two PHP pages which get and return some data from a small database that I have on my own site. You don't even need to know the details of how the PHP pages do their processing. You may regard my PHP pages as "black boxes" which return to you some information. What you do need to know is what kind of information is returned from the PHP pages.

The PHP pages return the following information (which is packaged as a JSON string). "JSON" stands for "JavaScript Object Notation". In JSON data, the data are packaged up as a string representation of JavaScript objects.

And please NOTE CAREFULLY that if you are going to make server pages like these two that I mention above, which allow users from other Web sites to access the page, you MUST INCLUDE AT THE VERY TOP OF THE PAGE (after the opening <?php marker, that is) a header statement like this:

  header("Access-Control-Allow-Origin: *");

If you don't include this header() statement, JavaScript will prevent access to the page, by users from other sites.


The Form Page

Let's look at the the form page for this e-handout. This is page AjaxForm5.html:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Dynamically Populate a Select List</title>
  <link rel="stylesheet" type="text/css" media="all" href="PHPstyles.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
    $.ajax({url:"http://www.jimlink.net/PHPStuff/getCategoryInfo5.php",
      type: "get",
      datatype: "json",
      success:function(result){
        var selectContents = "";
        selectContents += '<option value="0">-- Select a Category --</option>';
        var theCategories = $.parseJSON(result);
        var theRows = theCategories.rows;
        for (var i = 0; i < theRows.length; i++) {
          selectContents += "<option value='" + theRows[i].category_id + "'>" + theRows[i].category_name + "</option>";
        }
        $("#categoryID").html(selectContents);
      }
    });

    $('#categoryID').on("change", function()
    { 
      $.ajax({url:"http://www.jimlink.net/PHPStuff/getCategoryDetailInfo5.php?categoryID=" + $(this).val(),
          type: "get",
          datatype: "json",
          success:function(result){
          var selectContents2 = "";
          selectContents2 += '<option value="0">-- Select a Category Item --</option>';
          var theItems = $.parseJSON(result);
          var theRows2 = theItems.rows;
          for (var i = 0; i < theRows2.length; i++) {
            selectContents2 += "<option value='" + theRows2[i].category_detail_id + "'>" + theRows2[i].category_detail_name + "</option>";
          }
          $("#categoryDetail").html(selectContents2);
          }
      });
    });
      
      $(document).on("change", "#categoryDetail", function()
      { 
        var optionSelected = $(this).find("option:selected");
        var valueSelected  = optionSelected.val();
        var textSelected   = optionSelected.text();
        $('#youSelected').html(textSelected);
      });
    });
  </script>
</head>
<body>
  <div id="mainDiv">
    <form>
    <table>
    <tr>
      <td>Select a Category: </td>
      <td>
      <select name="categoryID" id="categoryID">
      </select>
      </td>
    </tr>
    <tr>
      <td>Select a Category Item: </td>
      <td>
      <select name="categoryDetail" id="categoryDetail">
    <option value="0">-- Select a Category Item --</option>
    </select>  
      </td>
    </tr>
    <tr>
      <td>You selected: </td>
      <td>
      <div id="youSelected">
      </div>  
      </td>
    </tr>
    </table>
    </form>
  </div>
</body>
</html>

Please note these points about the above code:


$.ajax() Details

Now here are some details about how to use the jQuery $.ajax() method to do AJAX processing:

The core part of AJAX processing is an asynchronous call to a Web-server-based page or program. This magic call is possible because all of the major browsers now support the JavaScript XMLHttpRequest object. Now the browser can communicate with the Web server from JavaScript code. This is significant! A Web server page can retrieve information, for instance, from a database; can format it into useful JavaScript information; and can then return it to the browser independently from any other JavaScript processing that the browser is running. This uncoupled, independent processing is a major part of what "asynchronous" means.

What the availability of the XMLHttpRequest object means for us in this current discussion is that the $.ajax() call must include the URL for a Web-server page. In the sample page in this e-handout, these two URLs look like this:
  url:"getCategoryInfo5.php"

and

  url:"getCategoryDetailInfo5.php"

Please note that the second URL in the actual sample page also includes some additional information. Specifically, it includes a URL variable which tells the server page which category ID was selected in the first select list. So this second URL actually looks like this:

  url:"getCategoryDetailInfo5.php?categoryID=" + $(this).val()

where the ? (question mark) begins the "query string" which has URL variables in it, and $(this).val() is a jQuery method which provides the value from the selected <option> tag in the select list.


Before things get too complicated here, let me list the four main parameters that the $.ajax() call normally requires. (We have just discussed the first one, which is the URL.) Here is a summary list of those four parameters:

  1. The URL of a Web-server page.
  2. The protocol type of the call. This is usually "GET".
  3. The data type of the returned information which will come back from the call to the server page. This is often "JSON". "JSON" stands for "JavaScript Object Notation". In JSON data, the data are packaged up as a string representation of JavaScript objects.
  4. A "success" function which will process the information that will be returned from the server page. This is often an anonymous function.

It is usually in the anonymous function in the "success" parameter where the most interesting processing takes place for an AJAX call. This is certainly the case in this sample page.


The Anonymous Function

Here are some of the most important details about the anonymous functions in this sample page:

The parameter, result, receives the returned information from the Web-server page. Please note that this anonymous function is called by the browser's internal AJAX processor when the information is successfully returned from the Web server. This return processing occurs after the rest of the JavaScript code has continued to run, which is why this process is called "AJAX", with the first "A" standing for "asynchronous". It could be several seconds (but not usually that long) before this "success" function gets called.

Both of the "success" functions in this sample page build the <option> tags for their respective select lists. The first <option> tag in each of the lists is a "dummy" tag which has a value of 0.

Both of these "success" functions receive their information in JSON format, which is basically a long string that represents the data as objects and/or arrays. So the jQuery $.parseJSON() method is used to "unpack" this JSON data into internal JavaScript objects.

The rows property of the returned objects is an array containing the data returned from the Web server's database tables. This array is processed by a for loop to retrieve the table's relevant data and to build the remaining <option> tags.

After the for loop has built the select list's <option> tags, the jQuery html() method is used to put these <option> tags into the appropriate <select> tag.


JSON Considerations

JSON is very sensitive to syntax and punctuation, meaning that the syntax and punctuation can easily break your JSON code.

Here are some of the most important JSON syntax and punctuation considerations: