You are on page 1of 45

JSON: JavaScript Object Notation.

JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.
JSON Example
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The employees object is an array of 3 employee records (objects).

What is JSON?

JSON stands for JavaScript Object Notation

JSON is lightweight text-data interchange format

JSON is language independent *

JSON is "self-describing" and easy to understand

* JSON uses JavaScript syntax for describing data objects, but JSON is still language and
platform independent. JSON parsers and JSON libraries exists for many different
programming languages.

JSON - Evaluates to JavaScript Objects


The JSON text format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, instead of using a parser, a JavaScript program can use the builtin eval() function and execute JSON data to produce native JavaScript objects.

JSON - Introduction
With our editor, you can edit JavaScript code online and click on a button to view the result:

JSON Example

<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p>
Name: <span id="jname"></span><br />
Age: <span id="jage"></span><br />
Address: <span id="jstreet"></span><br />
Phone: <span id="jphone"></span><br />
</p>
<script>
var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
</body>
</html>
Result

JSON Object Creation in JavaScript

Name: John Johnson


Age: 33
Address: Oslo West 16
Phone: 555 1234567

Much Like XML

JSON is plain text

JSON is "self-describing" (human readable)

JSON is hierarchical (values within values)

JSON can be parsed by JavaScript

JSON data can be transported using AJAX

Much Unlike XML

No end tag

Shorter

Quicker to read and write

Can be parsed using built-in JavaScript eval()

Uses arrays

No reserved words

Why JSON?
For AJAX applications, JSON is faster and easier than XML:
Using XML

Fetch an XML document

Use the XML DOM to loop through the document

Extract values and store in variables

Using JSON

Fetch a JSON string

eval() the JSON string

JSON Syntax
Previous

Next Chapter

JSON syntax is a subset of JavaScript syntax

JSON Syntax Rules


JSON syntax is a subset of the JavaScript object notation syntax:

Data is in name/value pairs

Data is separated by commas

Curly braces hold objects

Square brackets hold arrays

JSON Name/Value Pairs


JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed
by a value:

"firstName" : "John"
This is simple to understand, and equals to the JavaScript statement:

firstName = "John"

JSON Values
JSON values can be:

A number (integer or floating point)

A string (in double quotes)

A Boolean (true or false)

An array (in square brackets)

An object (in curly brackets)

null

JSON Objects
JSON objects are written inside curly brackets,
Objects can contain multiple name/values pairs:

{ "firstName":"John" , "lastName":"Doe" }
This is also simple to understand, and equals to the JavaScript statements:

firstName = "John"
lastName = "Doe"

JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
In the example above, the object "employees" is an array containing three objects. Each
object is a record of a person (with a first name and a last name).

JSON Uses JavaScript Syntax

Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within
JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:

Example
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
The first entry in the JavaScript object array can be accessed like this:

employees[0].firstName + " " + employees[0].lastName;


The returned content will be:

John Doe
The data can be modified like this:

employees[0].firstName = "Gilbert";
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>Original name: <span id="origname"></span></p>
<p>New name: <span id="newname"></span></p>

<script>
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" },
{ "firstName" : "Anna" , "lastName" : "Smith" },
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];

document.getElementById("origname").innerHTML=employees[0].firstName + " "


+ employees[0].lastName;

// Set new name


employees[0].firstName="Gilbert";
document.getElementById("newname").innerHTML=employees[0].firstName + " "
+ employees[0].lastName;
</script>

</body>
</html>
result:-

Create Object from JSON String

Original name: John Doe


New name: Gilbert Doe

JSON Files

The file type for JSON files is ".json"

The MIME type for JSON text is "application/json"

JSON HowTo
Previous
Next Chapter

Converting a JSON Text to a JavaScript Object


One of the most common use of JSON is to fetch JSON data from a web server (as a file or
as an HttpRequest), convert the JSON data to a JavaScript object, and then it uses the data
in a web page.
For simplicity, this can be demonstrated by using a string as input (instead of a file).

JSON Example - Object From String


Create a JavaScript string containing JSON syntax:

var txt = '{ "employees" : [' +


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be
used to convert a JSON text into a JavaScript object.
The eval() function uses the JavaScript compiler which will parse the JSON text and produce
a JavaScript object. The text must be wrapped in parenthesis to avoid a syntax error:

var obj = eval ("(" + txt + ")");


Use the JavaScript object in your page:

Example
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>

Try it yourself

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

var obj = eval ("(" + txt + ")");

document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
Result:Create Object from JSON String

First Name: Anna


Last Name: Smith

JSON Parser

The eval() function can compile and execute any JavaScript. This represents a potential security pro
It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser
will recognize only JSON text and will not compile scripts.
In browsers that provide native JSON support, JSON parsers are also faster.
Native JSON support is included in newer browsers and in the newest ECMAScript
(JavaScript) standard.
Web Browsers Support

Web Software Support

Firefox (Mozilla) 3.5

jQuery

Internet Explorer 8

Yahoo UI

Chrome

Prototype

Opera 10

Dojo

Safari 4

ECMAScript 1.5

Try it yourself

For older browsers, a JavaScript library is available


at https://github.com/douglascrockford/JSON-js
The JSON format was originally specified by Douglas Crockford

Introduction to JSON with PHP


Posted on 23 November, 2012 by Masud Alam

What is JSON, and what can it do? In this


tutorial you learn how to use JSON to easily move data around the web. You also
look at how to work with JSON using both JavaScript and PHP. If youve
developed websites or web apps at all, youve probably heard of JSON, at least
in passing. But what exactly is JSON? What can it do, and how do you use it? In
this tutorial youll learn the basics of JSON.
Youll look at the following topics:

What JSON does

The kinds of things JSON is used for

How to create JSON strings

A simple JSON example

How JSON compares to XML, and

How to work with JSON using both JavaScript and PHP.

Lets get started!


What is JSON?
JSON is a simple, text-based way to store and transmit structured data. By using
a simple syntax, you can easily store anything from a single number through to
strings, arrays, and objects using nothing but a string of plain text. You can also
nest arrays and objects, allowing you to create complex data structures.
Once youve created your JSON string, its easy to send it to another application
or computer, because its just plain text.

JSON has a lot of advantages:

Its compact

Its easy for both computers and people to read and write

It maps very easily onto the data structures used by most programming
languages (numbers, strings, booleans, nulls, arrays and associative

arrays)
Nearly all programming languages contain functions or libraries that can
read and write JSON structures

Note:
JSON stands for JavaScript Object Notation. As the name implies, its
based on the way you define objects (which are very similar to what
youd call associative arrays or hashes in other languages), and arrays.
How does it work?
JSON is capable of setting up data constructs for integers, strings, arrays, and
booleans the most essential data building blocks. Using a carefully defined
syntactical construct, JSON can be used to outline an object and with the use of
javascripts eval() function, they can be converted to a working object.
But the power does not end there. Other popular programming languages have
been implementing native support for JSON, such as PHP and ActionScript. For
example, PHP can now convert an associative array of data into a JSON string by
using the new json_encode() function, provided in version 5.2+ of the language.
For languages without native support, you can find a full range of
implementation classes available at the JSON website.
How to write JSON Syntax:
Declaration
All JSON objects are declared with a pair of curly braces. You can assign them to
a variable like you would any other data structure.

1var myObj = {}

Thats it! While not very powerful, this is all thats required to create
objects using JSON. So lets start adding some properties to this object.
Strings
We are going make this object represent me, so lets start by adding my name.

1var myObj = {name: 'Nahid'}

Lets take a second to carefully look at what we did here. We wanted to add a
property called name, and to do so, you simply write the property, name. We
follow the property label by a colon to separate the property name and its value.
To the right of the colon, comes the value. Since we wanted the value to be a
string, we put it in quotes.
With the JSON we have put in place, you are now able to access the property by
using the dot notation. To access a property, follow the Variable [dot] property
construct.

1alert(myObj.name) // "Nahid"

Integers
If we wanted to assign a property to the object of an integer data type, there is
no need to quote the value.

1var myObj = {age: 24}

Multiple properties are separated by a comma.

1var myObj = {name: 'Nahid', age: 24}

2
3
alert("My name is " + myObj.name + " and I'm " + myObj.age);

4
5

// "My name is Nahid and I'm 24

Booleans
Like integers, booleans are also unquoted

1var myObj = {name: 'Nahid', age: 24, engaged: true}

Arrays
Arrays can contain a collection of the previously mentioned data types. To define
an array, wrap the value in square brackets and separate the values with
commas.
Note: I will now add line breaks and indentation for legibility. It has no bearing
on the working order of the object.

1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 24,
6
7 engaged: true,
8
9
1

favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild']

0
1
}
1

You can access a value in an array in the object by using a combination of the
dot notation (to access the objects property) and index notation (to access an
indexed value of an array).

1alert(myObj.favorite_tv_shows[1]); // "Dirty Jobs"

To take the array complexity one step further, an array can also contain other
objects.

1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 24,
6
7 engaged: true,
8
9

favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],

1
0 family_members: [
1
1

{name: "Nahid", age: 27, relation: "father"},

1
2
1 {name: "Tina", age: 24, relation: "sister"}

3
1
4
1
5
1]
6
1
7}
1
8
1
9

This still requires dot and index notation, with an additional dot notation for
accessing the property of the object found in the indexed array value.

1alert(myObj.family_members[1].name) // "Tina"

There is one situation where you will use square brackets to access an objects
property and not the dot notation: when you are using a variable as the property
name. For example:

1 var myObj = {
2
3 name: 'Nahid',
4
5 age: 27,
6

7
8
9
1
0
1
1

engaged: true,

1 favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],


2
1
3 family_members: [
1
4

{name: "Nahid", age: 57, relation: "father"},

1
5
1
6

{name: "Tina", age: 26, relation: "sister"}

1]
7
1
}
8
1
9 var property = "age"
2
0
2
1
2
2
2
3

alert(myObj[property]); // "24"

Recap
Take some time experimenting with JSON and you will see that you can pick up
the concept and syntax rather quickly. As a caveat that may save you time in
the future: certain languages require you to quote the property names, such as
ActionScript. If not, it will complain.

1myObj = {name: "Nahid"} // will complain


2
3myObj = {"name": "Nahid"} // will work</pre>

Creating Object in JavaScript using JSON


We can create objects in JSON with JavaScript in many ways :
1.

var JSONObjectName ={}; will create an empty object.

2.

var JSONObjectName= new Object(); will create a new Object.

3.

var JSONObjectName = { name :Fahad, age:23}; will create an


Object with attribute name which contains value in String and age with
numeric value.

Now by creating this object we can access attributes by only . operator.


Here is the full example code for creating an Object in JavaScript using JSON:
ObjectJavaScript-JSON.htm

1 <html>
2 <head>
3 <title>
4 Object creation in JSON in JavaScript
5

</title>

6 <script language="javascript" >


7 var JSONObject = { "name" : "Fahad",
8

"address" : "420 Hatirpool",

"age" : 23,

1
0
1
1
1
2

"phone"

: "011-4565763",

"MobileNo" : 0981100092
};
document.write("<h2><font color='blue'>Name</font>::"
+JSONObject.name+"</h2>");

1 document.write("<h2><font color='blue'>Address</font>::"
3
+JSONObject.address+"</h2>");

1 document.write("<h2><font color='blue'>Age</font>::"
4
+JSONObject.age+"</h2>");

1
5 document.write("<h2><font color='blue'>Phone No.</font>::"
1 +JSONObject.phone+"</h2>");
6 document.write("<h2><font color='blue'>Mobile No.</font>::"
1
7

+JSONObject.MobileNo+"</h2>");
</script>

1
8 </head>

1 <body>
9 <h3>Example of object creation in JSON in JavaScript</h3>
2 </body>
0
</html>

2
1
2
2
2

3
2
4
2
5
2
6
2
7
2
8

Output:
Name::Fahad
Address::420 Hatirpool
Age::23
Phone No.::011-4565763
Mobile No.::981100092
Example of object creation in JSON in JavaScript
Creating Array Objects in JavaScript with JSON
In This example we have created an object students which contains two
array objects Maths and Science containing name, marks and age of two
students. Now we can access these objects value in the following way:
students.Maths for accessing Maths array and students.Science for
accessing Sciencearray object. Now to access first element of the Maths array
we can write it as students.Maths[1]and then we can access elements of
this array as students.Maths[1].Name for name

andstudents.Maths[1].Marks for marks of the first student in Maths and


so on.
Here is the full example code for JavaScript-JSONArray.htm file.

1 <html>
2 <head>
3 <title>
4 Array JSON-JavaScript Example
5
6
7

</title>
<script language="javascript" >
var students = { "Maths" : [

8
9

{"Name" : "Fahad", // First element


"Marks" : 67,

1
0 "age" : 23 },

1 {"Name" : "Vimrul", // Second element


1
"Marks" : 65,

1 "age" : 21 }
2
],

1
3 "Science" : [
1 {"Name" : "Mizan", // First Element
4
"Marks" : 56,

1
"age" : 27 },
5
1
6

{"Name" : "Mithu", // Second Element


"Marks" : 78,

1 "age" : 41 }
7

1 ]
8

1
9

// Printing all array values


var i=0

2
0 document.writeln("<table border='1'><tr>");
2 for(i=0;i<students.Maths.length;i++)
1
{

2
2

document.writeln("<td>");
document.writeln("<table border='0' width=100 >");

2
3

document.writeln("<tr><td><B>Name</B></td><td width=50>"

2
4

+students.Maths[i].Name+"</td></tr>");

2
5

+students.Maths[i].Marks +"</td></tr>");

document.writeln("<tr><td><B>Marks</B></td><td width=50>"

document.writeln("<tr><td><B>Age</B></td><td width=50>"

2
6

+students.Maths[i].age +"</td></tr>");
document.writeln("</table>");

2
7

document.writeln("</td>");

2 }
8

for(i=0;i<students.Science.length;i++)

2
9 {
3
0
3
1
3
2
3
3
3

document.writeln("<td>");
document.writeln("<table border='0' width=100 >");
document.writeln("<tr><td><B>Name</B></td><td width=50>"
+students.Science[i].Name+"</td></tr>");
document.writeln("<tr><td><B>Marks</B></td><td width=50>"
+students.Science[i].Marks +"</td></tr>");
document.writeln("<tr><td><B>Age</B></td><td width=50>"

+students.Science[i].age +"</td></tr>");
document.writeln("</table>");

3
5

document.writeln("</td>");

3 }
6
document.writeln("</tr></table>");

3
7 </script>
3 </head>
8 <body>

3 Using Array of objects via JSON in JavaScript


9
</body>

4
0 </html>
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5

0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0

Output:

How to create and read JSON strings in PHP

PHP, like JavaScript, has functions that can convert variables to JSON strings and
vice-versa. Lets take a look at them.

C R E AT I N G A J S O N S T R I N G F R O M A P H P VA R I A B L E

json_encode() takes a PHP variable and returns a JSON string representing the
variable. Heres our shopping cart example written in PHP:

1 <?php
2
3 $cart = array(
4
5

"orderID" => 12345,

6
7

"shopperName" => "Faisal Ahmed",

8
9
1
0

"shopperEmail" => "faisal@gmail.com",

"contents" => array(

1
1
array(

1
2
1
3

"productID" => 34,

1
4

"productName" => "SuperWidget",

1
5
"quantity" => 1

1
6
1
7

),

1
8

array(

1
9

"productID" => 56,

2
0
"productName" => "WonderWidget",

2
1

"quantity" => 3

2
2
2
3
2
4
2
5

),

"orderCompleted" => true

2
6
2
7

);

2 echo json_encode( $cart );


8
2
9 ?>
3

0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1

This produces exactly the same output as our JavaScript example a valid JSON
string representing the variables contents:
Output:

{orderID:12345,shopperName:Faisal
Ahmed,shopperEmail:faisal@gmail.com,contents:
[{"productID":34,"productName":"SuperWidget","quantity":1},
{"productID":56,"productName":"WonderWidget","quantity":3}],orderCompl
eted:true}In a real-world online store, your PHP script would send this JSON

string as part of the Ajax response back to the browser, where the JavaScript
code would use JSON.parse() to turn the string back into a variable so it can
display the carts contents to the shopper.
Note: You can also pass various flags as a second argument to json_encode().
These let you do things like encode certain special characters using hex notation
to make the string more portable, and force empty and indexed arrays to be
encoded as objects (associative arrays). Find out more.

C R E AT I N G A P H P VA R I A B L E F R O M A J S O N S T R I N G

To go the other way and convert a JSON string into a PHP variable, you use
you guessed it json_decode(). Lets rewrite our JavaScript JSON.parse()
example in PHP:

1 <?php
2
3 $jsonString = '
4
5 {
6
7

"orderID": 12345,

8
9
1
0
1
1
1
2

"shopperName": "Faisal Ahmed",

"shopperEmail": "faisal@gmail.com",

"contents": [

1
3

1
4

"productID": 34,

1
5

"productName": "SuperWidget",

1
6

"quantity": 1

1
7
1
8

},

1
9

2
0

"productID": 56,

2
1

"productName": "WonderWidget",

2
2
"quantity": 3

2
3
}

2
4
2
5

],

2
6
2
7

"orderCompleted": true

2
8
2

';

9
3 $cart = json_decode( $jsonString );
0
3
echo $cart->shopperEmail . "<br>";
1
3
2 echo $cart->contents[1]->productName . "<br>";
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4

?>

5
4
6
4
7
4
8
4
9

As with the JavaScript version, this produces the following output:


faisal@gmail.com
WonderWidget
By default, json_decode() returns JSON objects as actual PHP objects. These
are generic PHP objects of the stdClass class. Thats why we used -> to access
the objects properties in the example above.
If youd rather return JSON objects as PHP associative arrays, just pass true as a
second argument to json_decode(). For example:

1$cart = json_decode( $jsonString, true );


2
3echo $cart["shopperEmail"] . "<br>";
4
5echo $cart["contents"][1]["productName"] . "<br>";

This displays the same output:


faisal@gmail.com
WonderWidget
Convert a PHP Class to JSON

As json_encode() is recursive, you can use it to serialize whole structure of


objects.

1 </pre>
2 <?php
3
4 class A {
5
6 public $a = 1;
7
8

public $b = 2;

9
1
0

public $collection = array();

1 function __construct(){
1
1
2 for ( $i=3; $i>0; $i--){
1
3 array_push($this->collection, new B);
1
4
1
5

1 }
6
1
}
7
1
8

1
9
2
0
2
1
2
2
2
3

class B {

2
4
2
5

public $a = 1;

2 public $b = 2;
6
2
7 }
2 echo "<pre>";
8 echo json_encode(new A);
2
9
3
0
3
1
3
2
3
3
3
4

?>

Willgive:

"a":1,

"b":2,

"collection":[{

"a":1,

"b":2

},{

"a":1,

"b":2

},{

"a":1,

"b":2

}]

Combining PHP, JSON and jQuery


Now Ill show you how simple it is to make PHP communicate with a JSON data
source using jQuerys Ajax functionality.
Step 1:
First were going to create a form with a dynamic dropdown. The dropdown will
show a list of cities that we retrieve from a JSON datasource.
Step 2:
Our first step is to create the script that sends the JSON data. We load up our
editor. Ive already created a few blank scripts here but well fill these in as we
go.
Step 3:
So json.php. We create an array. This is just a PHP array with a list of cities.
Adelaide, Perth, Melbourne Sydney. And we can send back this in JSON format
which is basically just JavaScript code using json_encode(). We just pass the
array and save the script.

Step 4:
Now, back in Chrome we load the file (index.php). Thats the array we just
created. If you actually look in developer tools, the script is here under
resources. Its sent it with content type text/html. Technically this isnt really a
problem. It will work, but to be correct it needs to be application/json content
type.
Step 5:
So just back in json.php use the header() function, content-type and then save,
reload. Now if we look here, its application/json and Chrome gives us a warning
here, thats just because we tried to display it as a normal HTML page even
though its not.
Listing 1 The JSON data source (json.php)

1
2 <?php
3

$cities = array(
'Adelaide',

'Perth',

'Melbourne',

'Sydney'

7
8
9
1
0
1
1

);

header('Content-type: application/json');
echo json_encode($cities);
?>

Step 6:
Thats the data source done. Next were going to create some JavaScript to

actually output that. Lets go back here. The script well just update now to load
a select box. Now this doesnt actually do anything, all were going to do is
populate this. So lets call it city, and give it an id of #city-list, so we can refer to
it later in our JavaScript. And well just put a blank element that instructs the
user to select a city. And we save that, and then go back to the index.php script.
Step 7:
Now weve got this dropdown which well populate shortly. Were using jQuery in
this. To make things a little bit simpler were going to use Googles hosted
version of jQuery. We can search Google jQuery and I think its the first link. So
we just click on jQuery and it shows you the versions that they host. You can
either use their loader or just go straight to the path. Well get the minified
version (jquery.min.js) because it loads quicker. We dont need the full source
code.
Step 8:
So lets just load that here. So thats all we need to do to import jQuery into our
script, and were about to create this script.js file, so well just load that one as
well.
The main index file that displays the form (index.php)

1 <html>
2
3
4
5
6
7
8
9
1

<head>
<title>JSON Example - w3programmers.com</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div>
<h1>PHP + jQuery Example - PhpRiot.com</h1>
<select name="city" id="city-list">

0
1
1
<option value="">Select a city...</option>

1
2
1
3

</select>
</div>
</body>

1 </html>
4
1
5

Step 8:
Okay so thats now loading, it doesnt actually do anything yet, but what we can
do is just ensure that jQuery is loaded. So this is the on dom loaded event.
Save that one and go back to the browser. We dont need this any more, now
refresh. Hopefully well get an alert box just to ensure that jQuery is loaded, and
there we go. That means we can keep going.
Step 9:
Now, we go back, we can remove this alert. Now what we want to do is use the
jQuery getJSON() function. So for that, we call $.getJSON(). The script is called
json.php, so put that in, and the callback is the second argument, and when the
callback is called the data returned from the script is passed as the first
argument.
Step 10:
So thats our placeholder. You can have a look at that before we do anything
with it. Just throw in a console.log(), pass the data, save and return the Chrome.
Now if you load developer tools. Lets refresh this page. So now you can see this
script here after the JavaScript is loaded it performed the JSON query. So thats
what we created earlier on but you can this output that we wrote to the console.
So were most of the way there, all we need to do now is use this data to
populate the select box.

Step 11:
So returning to our editor. So we just call $.each(), pass the array as the first
argument and the callback as the second. The first argument to the callback is
the index, so 0, 1, 2, 3 in this case, and the second argument is the value, which
is the name of the city, which is what were going to use.
Step 12:
For each iteration of this loop were going to write a new option to the select
box. So first we need to get the select box. So were going to call it var select,
and we called that #city-list, and then in each iteration option, create the new
option, so we set the value attribute, so when the form is submitted the value is
passed in, and we set the HTML using the .html() function, so we just pass the
city name again. And finally we append it to the select, so appendTo(select).
JavaScript to populate the select box with JSON (script.js)

1
2 jQuery(function($) {
$.getJSON('json.php', function(json) {

var select = $('#city-list');

$.each(json, function(k, v) {

var option = $('<option />');

option.attr('value', v)

.html(v)

.appendTo(select);

});

1
0
1
1

});
});

Final:
Now we can save, return to Chrome, and refresh. Now weve got our developer
tools still open so you can see theyre all appearing here, and in the dropdown.
And thats all there is to it! Now we havent actually done anything with this list,
but you can use this inside your normal forms, or you can trigger the load after a
particular btuton is pressed. Here weve just made it simple and doing it onload,
but you can really do it however you need to.
Combining PHP, JSON, MySQL and jQuery
1.

json-jquery.js js file to request the data

2.

json-data.php php file to connect to database to retrieve data

3.

page.html html page to call/display data

J S O N - J Q U E RY. J S

1 $(document).ready(function(){
2
3

//attach a jQuery live event to the button

4
5

$('#getdata-button').live('click', function(){

6
7

$.getJSON('json-data.php', function(data) {

8
9
1
0
1
1

//alert(data); //uncomment this for debug

//alert (data.item1+" "+data.item2+" "+data.item3); //further debug

$('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+"
item3="+data.item3+"</p>");
1

1
3
1
4
1
5

});

1
6

});

1
7
1
8

});

1
9

J S O N - D ATA . P H P

1 <?php
2
3 //request data from the database
4
5 //code here to connect to database and get the data you want
6
7 /* Example JSON format
8
9
1
0
1

"item1": "I love PHP and JSON",

"item2": "You love PHP and JSON",

1
2

"item3": "We love PHP and JSON"

1
3
1
4

1 */
5
1
//return in JSON format
6
1
7 echo "{";
1
8

echo "item1: ", json_encode($item1), "\n";

1
9
2 echo "item2: ", json_encode($item2), "\n";
0
2 echo "item3: ", json_encode($item3), "\n";
1
2
2 echo "}";
2
3
2
4
2
5
2
6
2

?>

7
2
8
2
9
3
0
3
1
3
2
3
3

Alternative methods
Create an array in PHP and use the json_encode() function to encode
the whole array.
?

1<?php
2
$arr = array ('item1'=>"I love jquery4u",'item2'=>"You love jQuery4u",'item3'=>"We love
jQuery4u");

3
4
5

echo json_encode($arr);

6
7?>

This will output the array in the correct JSON format; however it may not include
line breaks as the previous example shows so make sure you check this by
alerting the data. There is also a json_decode() function which does the
opposite.

page.html

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "


2
3

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<html xmlns=" http://www.w3.org/1999/xhtml ">

4
5

<head>

6
7

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

8
9

<title>Request json test</title>

1
0
1
1

<script src="http://code.jquery.com/jquery-1.5.js"></script>

1 <script src="json-jquery.js" type="text/javascript"></script>


2
1
</head>
3
1
4 <body>
1
5

<a href="#" id="getdata-button">Get JSON Data</a>

1
6
1 <div id="showdata"></div>
7
1 </body>
8

1
9
2
0
2
1
2
2 </html>
2
3
2
4
2
5
This entry was posted in Featured Posts, JSON, XML and Web Services and
tagged json by Masud Alam. Bookmark the permalink.

You might also like