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.
<?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>
{"site": {"categ": "Web Programming"}}
{"url": "https://coursesweb.net/php-mysql/"}
{"site": { "categ": "Web Programming", "url": "https://coursesweb.net/php-mysql/", "descriere": "Free PHP-MySQL online course and tutorials" }}
{"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.
<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>
<?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.
<!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" /> 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.
<?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 } ?>
<!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.
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net