JSON
- JavaScript Object Notation
- A Simple format designed to exchange data between different programming language
- Creating with JavaScript
var JSONstring = { "firstname": "Greg", "email": "greg@fake_email.com", "hobby": [ { "hobbyName": "sport", "isHobby": "true" }, { "hobbyName": "reading", "isHobby": "true" }, { "hobbyName": "music", "isHobby": "false" } ] };
- Accessing with JavaScript
JSONstring.hobby[1].isHobby; // trueCreating JavaScript Objects
- JavaScript object <-> JSON string : http://www.json.org/json2.js
- Example
<html> <head><TITLE>ditio.net jSon Tutorial</TITLE> <script src="http://www.json.org/json2.js"></script> <script> // JavaScript source code will be here function validate() { var p = document.forms['personal']; var JSONObject = new Object; JSONObject.firstname = p['firstname'].value; JSONObject.email = p['email'].value; JSONObject.hobby = new Array; for(var i=0; i<3; i++) { JSONObject.hobby[i] = new Object; JSONObject.hobby[i].hobbyName = p['hobby'][i].value; JSONObject.hobby[i].isHobby = p['hobby'][i].checked; } JSONstring = JSON.stringify(JSONObject); runAjax(JSONstring); } </head> <body> <form name="personal" action="" method="POST"> Name <input type="text" name="firstname"><br> Email <input type="text" name="email"><br> Hobby <input type="checkbox" name="hobby" value="sport"> Sport <input type="checkbox" name="hobby" value="reading"> Reading <input type="checkbox" name="hobby" value="music"> Music <input type="button" name="valid" value="Validate" onclick="validate()"> </form> </body> </html>Sending JSON object to PHP with AJAX
- Example
var request; function runAjax(JSONstring) { // function returns "AJAX" object, depending on web browser // this is not native JS function! request = getHTTPObject(); request.onreadystatechange = sendData; request.open("GET", "parser.php?json="+JSONstring, true); request.send(null); } // function is executed when var request state changes function sendData() { // if request object received response if(request.readyState == 4) { // parser.php response var JSONtext = request.responseText; // convert received string to JavaScript object var JSONobject = JSON.parse(JSONtext); // notice how variables are used var msg = "Number of errors: "+JSONobject.errorsNum+ " - "+JSONobject.error[0]+ " - "+JSONobject.error[1]; alert(msg); } }