Advanced AJAX

Producing JSON data in PHP, Advanced DOM manipulation, Third party JavaScript libraries

AJAX with JSON

In the previous lab, you worked on AJAX with plain text. As a matter of fact, you can deal with AJAX data with various formats such as plain text, XML and JSON. Since many applications use JSON as data transferring structure, this lab introduces basics of JSON, producing JSON data in PHP and parsing JSON data in PHP.

What is JSON?

JSON stands for JavaScript Object Notation. It provides a structured way of storing and exchanging data. JSON supports various of data types such as string, number, boolean, array, null type and object.

JSON tutorial: http://www.w3schools.com/js/js_json_js_intro.asp

JSON syntax: http://www.w3schools.com/js/js_json_syntax.asp

Producing JSON in PHP

JSON Encoding in PHP5.5: http://php.net/manual/en/function.json-encode.php

Parsing JSON in PHP

JSON Decoding in PHP5.5: http://php.net/manual/en/function.json-decode.php

Third Party JavaScript Library: jQuery

jQuery is a third party JavaScript library that simplifies client-side programming.

jQuery introduction: http://www.w3schools.com/jquery/default.asp

jQuery syntax: http://www.w3schools.com/jquery/jquery_syntax.asp

jQuery selectors: http://www.w3schools.com/jquery/jquery_selectors.asp

jQuery AJAX: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

jQuery AJAX methods: http://www.w3schools.com/jquery/jquery_ref_ajax.asp

Advanced DOM Operation

This section gives two examples on AJAX. One uses basic JavaScript DOM operations that you have learned in previous lab. The other uses jQuery and JSON.

Example 1: Obtaning MySQL data with AJAX

AJAX with MySQL: http://www.w3schools.com/php/php_ajax_database.asp

Example 2: AJAX with jQuery and JSON

Many practical applications deal with a large volumn of data. You may find it rather difficult to retrieve all the data and display them in one single HTML page. The following provides a simple example on how to obtaining partial data and display them in a table with maximum five rows.

page1

page2

Demo Link of Example 2 and Source code

HTML link: demo (JavaScript code, CSS and HTML Code can be viewed by Firefox browser)

PHP source code:

Details of Example Two

This section shows main steps of the demonstration in example 2.

MySQL Support

MySQL database systems support obtaining certain amount of data at a time by using the keyword limit. For example,

mysql> select student_ID, last_Name, course_Name, marks from students 
where trim(last_Name) is not null and trim(last_Name)!='' limit 1,5;

+------------+-----------+-------------+-------+
| student_ID | last_Name | course_Name | marks |
+------------+-----------+-------------+-------+
| 200266200  | Abbad     | CS110       |    85 |
| 200266200  | Abbad     | CS210       |    90 |
| 200266202  | Rai       | CS100       |  72.5 |
| 200266202  | Rai       | CS110       |  59.2 |
| 200266202  | Rai       | CS215       |  82.6 |
+------------+-----------+-------------+-------+
5 rows in set (0.00 sec)

In the example, 1 is the offset from the initial row that starts from 0. The number 5 allows maximum five rows to return. That is, limit 1, 5 actually returns records from the 2nd row to the 6th row.

In PHP: Encoding data into JSON with PHP function json_encode()

Using php function json_encode() to encode your data into JSON format is a convenient way and it is recommended.

$sql2 = "select student_ID, last_Name, course_Name, marks from students 
where trim(last_Name) is not null and trim(last_Name)!='' limit " . $startRecord . ",5";

$result = mysqli_query($conn, $sql2);

$sResp[] =  array();

while ($row = mysqli_fetch_assoc($result))
{
    $sRow["stid"]=$row["student_ID"];
    $sRow["lname"]=$row["last_Name"];
    $sRow["course"]=$row["course_Name"];
    $sRow["marks"]=$row['marks'];
    $sResp[] = $sRow;
}
echo json_encode($sResp);

In PHP: Manually Encoding Data into JSON String

If your web server does not support the json_encode() function, you need to manually encode the data into JSON format, which means: concatenating strings following JSON format.

$sql2 = "select student_ID, last_Name, course_Name, marks from students 
where trim(last_Name) is not null and trim(last_Name)!='' limit " . $startRecord . ",5";

$result = mysqli_query($conn, $sql2);

sResp .= '[';
while ($row = mysqli_fetch_assoc($result))
{
     $sResp .= "{";
     $sResp .= '"stid":"' . $row["student_ID"]. '",';
     $sResp .= '"lname":"' . $row['last_Name']. '",';
     $sResp .= '"course":"' . $row['course_Name']. '",';
     $sResp .= '"marks":"' . $row['marks']. '"';
     $sResp .= "},";
}
// remove the last comma, i.e., ","
$sResp = substr($sResp, 0, -1);
$sResp .= "]";
echo $sResp;

Configuring AJAX and Sending an HTTP Request

The function ajaxSetup() specifies basic configurations for later AJAX calls.

$.ajaxSetup({
  url: 'example.php',
  type: 'post',
  
  // parameter to be sent (optional)
  // it can be sent while actually making an HTTP request
  // data: {index: myIndex}, 
  
  // set response datatype as JSON and jQuery decodes it automatically
  // that is, use the data as JS object directly
  dataType: 'json', 
  
  // successful handler
  success: displayJsonData, 
  
  // error handler
  error: printerror 
});

Parameters and Values

Paramters and corresponding values to be send to server can be defined in a variable:

var mydata = {
		// value from an input text box with a name="Searchname"
		mysearchname: $('input[name=Searchname]').val(),

		// value from a radio box selected by a user
		// the radio button has an attribute: name="mychoice"
		myradiobutton: $('input:radio[name=mychoice]:checked').val()
	};

Sending an AJAX Request

When actually sending an AJAX request to server (PHP), use function ajax(). You can pass parameters, i.e., mydata, which you defined early.

$.ajax({data:mydata});

Dealing with Response

Function displayJsonData(myArr) is a success handler that outputs the result into a table with a <tbody id="tbodyResult">.

We do not need to parse JSON data since jQuery automatically did it for you. As a result, jQuery treats the parameter myArr as an object array.

function displayJsonData(myArr){
    if(myArr==null || myArr.length<=0){
    	$("#tbodyResult").empty();
	return;
    }

    var row="";
    // Note: normally i starts with 0, in this example, 
    // we start with 1
    for(var i = 1; i < myArr.length; i++) {
        row += '' + myArr[i].stid + ''; 
        row += '' + myArr[i].lname + ''; 
        row += '' + myArr[i].course + ''; 
        row += '' + myArr[i].marks + ''; 
    }
    $("#tbodyResult").html(row);
}

In Class Exercise Lab Assignment

You have completed the assignment of lab 10 where you use HTML forms to send the HTTP request to the server. The task of this assignment is using AJAX to make the request and displaying the results. The following image displays an sample output.

sample output

Link lab12.html on your index.html, zero if not linked on index.html

Zip lab12.html and lab12.php together and name it yourusername_lab12.zip and submit on URcourses by 11:55 PM.