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

JavaScript Timing

JavaScript Timing Events allows execution of code at specified time intervals.

These time intervals are called timing events. The two key methods to use with JavaScript are:
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.

https://www.w3schools.com/js/js_timing.asp

Example 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 an example on how to obtaining partial data and display them in a table with maximum five rows.

page1

page2

Demo Link of the example and Source code

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

PHP source code:

Details of the Example

This section explains main steps of the example.

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);

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 sign up page for lab10 by using php and MySql.

The task of this assignment is using AJAX to make the request and displaying the results in JSON format.

The following image displays the 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.