Ajax Course

JSON (JavaScript Object Notation) is a format for structuring data in a simple text format used for exchanging information, and can be used as a lighter alternative to XML.
Although it contains a minimal and simple set of rules, JSON can represent a complex data structure that can include arrays and objects in text format. In addition, JSON syntax is a subset of the JavaScript language, the data in JSON format can be easily processed in JavaScript. PHP also contains special functions for working with JSON (json_encode() and json_decode()). Due to these capabilities, JSON has become increasingly used and preferred in programs with data transfer between applications, especially in Ajax technology, often replacing the XML format.

1. Transform XML to JSON

Ajax is a technology for transferring data between the client and server, in some cases it uses the structure of XML document to store and process such data. A JSON format is a simpler alternative to pack and store the data to be transmitted and /or received by Ajax, which has the advantage of integration into JavaScript, making it much easier to process than XML.
Below is shown how to rewrite an XML document in JSON format. Consider the following XML model:

XML Document

<?xml version="1.0" encoding="utf-8"?>
<webcourses>
  <site categ="Web Programming">
    <url>https://coursesweb.net/php-mysql/</url>
    <description>Free PHP-MySQL online course and tutorials</description>
  </site>
  <site categ="Foreign languages">
    <url>https://marplo.net/engleza</url>
    <description>Free online English lessons</description>
  </site>
</webcourses>

Here's how the following XML element can be written in JSON:
<site categ="Web Programming">
- With JSON:
{"site": {"categ": "Web Programming"}}

The next XML element:
<url>https://coursesweb.net/php-mysql/</url>
- In JSON format:
{"url": "https://coursesweb.net/php-mysql/"}

Following the same model, we convert the content of the first XML "site" tag:
<site categ="Web Programming">
    <url>https://coursesweb.net/php-mysql/</url>
    <description>Free PHP-MySQL online course and tutorials</description>
</site>
- In JSON format:
{"site": {
  "categ": "Web Programming",
  "url": "https://coursesweb.net/php-mysql/",
  "descriere": "Free PHP-MySQL online course and tutorials"
}}

The logic is simple, the tags and their content, attributes and values of the XML document, are written in the JSON format as pairs "tag": "value" or "attribute": "value", added inside braces to follow the order and hierarchy of elements in the XML, and separated by commas.
The entire content of the XML document presented above can be written in JSON format, like this:
{"webcourses":
  [
    {"site": {
      "categ": "Web Programming",
      "url": "https://coursesweb.net/php-mysql/",
      "description": "Free PHP-MySQL online course and tutorials"
    }},
    {"site": {
      "categ": "Foreign languages",
      "url": "https://marplo.net/engleza",
      "descriere": "Free online English lessons"
    }}
  ]
}
- Data in JSON format can be processed in JavaScript directly as an multiple Array, thus "webcourses" will contain an associative array (defined between two square brackets [] ) with two keys (0 and 1). The value of first index [0] is an object with the content of the first "site" element, and the value of index [1] is an object with the content of the second "site" tag.

In the fallowing example you can see how easily is to access the data stored in JSON format.
<script type="text/javascript"><!--
// Data stored in JSON format
var json_obj = {"webcourses":
  [
    {"site": {
      "categ": "Web Programming",
      "url": "https://coursesweb.net/php-mysql/",
      "description": "Free PHP-MySQL online course and tutorials"
    }},
    {"site": {
      "categ": "Foreign languages",
      "url": "https://marplo.net/engleza",
      "descriere": "Free online English lessons"
    }}
  ]
};

// gets the value of "url" element from the first "site" element
document.write(json_obj.webcourses[0].site.url + '<br />');              // https://coursesweb.net/php-mysql/

// gets the value of the "categ" element from the second "site" element
document.write(json_obj.webcourses[1].site.categ);                 // Foreign languages
--></script>

2. Transferring JSON data with AJAX

Data from Forms, Array or other variables defined in script, that must be sent with Ajax to the server, can be set in JSON format and sent to the server in a single variable.
Below is presented a simple example in which the text written in the fields of a form is submitted by Ajax to a PHP script, in a JSON text string.
Here are the codes for the PHP script and the HTML page with the form and the Ajax script (See explanations from the code).

Code for the PHP script (test_ajaxjson.php)

<?php
// if data is received via POST, with index of 'jsn'
if (isset($_POST['jsn'])) {
  $sir_json = $_POST['jsn'];         // gets data

  // Remove any slashes added by "get_magic_quotes_gpc"
  if(get_magic_quotes_gpc()) { $sir_json = stripslashes($sir_json); }

  $arr_sir = json_decode($sir_json, true);         // Decode the JSON string and turn it into an Array

  // Returns the Array format, obtained from the JSON string
  echo '<pre>';
  var_export($arr_sir);
  echo '</pre>';
}
?>
- json_decode() is a PHP function that convert a JSON string inta an Array for PHP language.

Code for the HTML page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Ajax JSON</title>

<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
  // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
  var xmlHttp = null;

  if(window.XMLHttpRequest) {    // for Forefox, IE7+, Opera, Safari, ...
    xmlHttp = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {  // for Internet Explorer 5 or 6
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return xmlHttp;
}


// this function sends data to a php script and display the response
function ajax_json(php_file, tagID) {
  var request =  get_XmlHttp();    // calls the function for the XMLHttpRequest instance

  // Get selected radio button value
  if (document.getElementById('starec1').checked) var radio_b = document.getElementById('starec1').value;
  else if (document.getElementById('starec2').checked) var radio_b = document.getElementById('starec2').value;
  else var radio_b = 'Not Specified';

  // gets the text from form fields and define data in a JSON string
  var  date_jsn = '{"name1":"'+ document.f_test.name1.value+ '", "email1":"'+ document.f_test.email1.value+ '", "starec":"'+ radio_b+ '"}';

  var date_send = 'jsn='+date_jsn;            // Adds the JSON string in the variable that must be sent to the PHP script

  request.open("POST", php_file, true);      // sets the request

  // adds a header to tell the PHP script to recognize the data as is sent via POST
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(date_send);         // sends the request

  // Check request status
  // If the response is received completely, will be transferred to the HTML tag with tagID
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      document.getElementById(tagID).innerHTML = request.responseText;
    }
  }
}
--></script>
</head>
<body>

<div id="resp">Here will be displayed the response from the PHP script</div>
<form action="" method="post" name="f_test">
 <h5>Fill in the following data</h5>
  Name: <input name="name1" type="text" /><br />
  E-mail: <input name="email1" type="text" /><br />
  Marital status:<br />
  Married <input type="radio" name="starec" id="starec1" value="Married" /> &nbsp;
  Single <input type="radio" name="starec" id="starec2" value="Single" /><br />
  <input type="button" value="Send" onclick="ajax_json('test_ajaxjson.php', 'resp')" />
</form>

</body>
</html>
- You can test the result of this script with the form below.
You will notice that the data submitted are easily converted directly into an array specific PHP language.
Here will be displayed the response from the PHP script
Fill in the following data
Name:
E-mail:
Marital status:
Married   Single

3. Using Ajax with data received in JSON format

JSON format can be useful in data received by Ajax from the server.
With this format can be defined and sent directly from the server JavaScript objects or arrays, that can be used or executed directly in the JS script.
The fallowing example use a PHP script that receives a name from Ajax, makes an Array with some data and that name and returns this Array to Ajax, in a JSON format.
Ajax script will display the JSON string as it is received (More explanations are in the code documentation).

Code for the PHP script (test2_ajaxjson.php)

<?php
// if data is received via POST, with index of 'name2'
if (isset($_POST['name2'])) {
  $dat_got = $_POST['name2'];         // Preia datele primite

  // Remove any slashes added by "get_magic_quotes_gpc"
  if(get_magic_quotes_gpc()) { $dat_got = stripslashes($dat_got); }

  // Defines an array of data to be sent back to Ajax (can be any data, for example, some data from MySQL server)
  $dat_send = array($dat_got=>array('data 1', 'data 2', 'data 3'));
  $dat_send = json_encode($dat_send);         // Encode data to be returned in JSON format

  // Add slashes if "get_magic_quotes_gpc()" is not enabled
  // - becouse, if it is enabled, will add itself slashes, and Ajax script is defined to remove these slashes
  if(!get_magic_quotes_gpc()) { $dat_send = addslashes($dat_send); }

  echo $dat_send;         // return the response
}
?>

Code for the HTML page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Ex2 Ajax JSON</title>

<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
  // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
  var xmlHttp = null;

  if(window.XMLHttpRequest) {    // for Forefox, IE7+, Opera, Safari, ...
    xmlHttp = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {  // for Internet Explorer 5 or 6
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return xmlHttp;
}


// this function sends data to a php script and display the response
function ajax_json(php_file, tagID) {
  var request =  get_XmlHttp();    // calls the function for the XMLHttpRequest instance

  var f_nume = document.f_test2.name2.value;        // gets the name from form field
  var date_send = 'name2='+f_nume;            // defines data that must be sent to the PHP script

  request.open("POST", php_file, true);      // sets the request

  // adds a header to tell the PHP script to recognize the data as is sent via POST
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(date_send);       // sends the request

  // Check request status
  // If the response is received completely, will be transferred to the HTML tag with tagID
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
    var ex_ajsn = request.responseText;         // puts in a variable the received data
    ex_ajsn = ex_ajsn.replace(/\\/gi, '');          // remove the slashes "\" added in the php script
    document.getElementById(tagID).innerHTML = ex_ajsn;        // adds in the "tagID" the data received

    // Compiles with eval the data from "ex_ajsn" in another variable "obj_ajsn" (to fit in the JS language)
    eval("var obj_ajsn ="+ex_ajsn);

    // Knowing that you get a JavaScript Array object, the values can be easily retrieved using the index of each element
    // for example, adds in the "tagID" the data set and returned from the php script
    document.getElementById(tagID).innerHTML += '<br /><br />Data returned for: <b>'+ f_nume+ '</b> = <i>'+ obj_ajsn[f_nume]+ '</i>';
    document.getElementById(tagID).innerHTML += '<br />The second value defined for: <b>'+ f_nume+ '</b> = <i>'+ obj_ajsn[f_nume][1]+ '</i><br /><br />';
    }
  }
}
--></script>
</head>
<body>

<div id="resp2">Here will be displayed the JSON response from the PHP script and data from this response, processed by JavaScript</div>

<form action="test2_ajaxjson.php" method="post" name="f_test2" onclick="ajax_json('test2_ajaxjson.php', 'resp2'); return false">
  Your name: <input name="name2" type="text" /><br />
  <input type="submit" value="Send" />
</form>

</body>
</html>
- Notice how the eval() function is used with the JSON string received from PHP, to integrate it in the JS language, and how easily can be than to access any value from the JSON string.
- You can test the result of this script with the following form.
Here will be displayed the JSON response from the PHP script and data from this response, processed by JavaScript
Your Name:

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <img> tag for the address of the image?
href src rel
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;
#id {
  display: none;
}
What instruction stops the execution of a while() or for() statement?
continue prompt() break
for(var i = 0; i< 8; i++) {
  if(i > 1) break;
  alert(i);
}
Indicate the function that can create a constant.
define() include() defined()
define("CONSTANT_NAME", "value");
echo CONSTANT_NAME;
AJAX and JSON

Last accessed pages

  1. Prayer The Art of Believing (1589)
  2. SHA1 Encrypt data in JavaScript (35259)
  3. Detect when ScrollBar reaches the bottom of the page (4357)
  4. Common PHP Errors and Solutions (9661)
  5. Configuring Text (451)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (470)
  2. Read Excel file data in PHP - PhpExcelReader (147)
  3. PHP Unzipper - Extract Zip, Rar Archives (145)
  4. SHA1 Encrypt data in JavaScript (122)
  5. Get and Modify content of an Iframe (108)