callback methods / anonymous functions: jQuery

Today lets see how callback methods or anonymous functions work. We also show you the anatomy of callback methods.

callback-method-anonymous-function-javascript-jquery-nodejs

callback methods are very important for achieving asynchronous way of coding.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE html>
<html>
<head>
<title>callback or anonymous function</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<p></p>
<div></div>
 
</body>
</html>

Here we have included jQuery library and myScript.js We also have a paragraph tag and a div tag, to be filled with some data by myScript.js file.

JavaScript file
myScript.js

1
2
3
4
$(document).ready(function(){
 $("p").hide("slow");
 alert("Stop!");
});

Here the paragraph hide is called and before it finishes hiding, alert is called and every other operation of the webpage is halt until the user responds to the alert window. But if we want the paragraph to be hidden first and only after the paragraph is completely hidden we need to call the alert, in such case use callback methods as shown below:

JavaScript file: callback method
myScript.js

1
2
3
4
5
$(document).ready(function(){
 $("p").hide("slow", function(){
        alert("Stop!");
 });
});

If you want multiple things to occur after hiding the text(in above case) , you can nest the callback methods.

Anatomy of callback methods
JavaScript file: callback method
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function(){
	eat("pizza", "cola", function(){
	$("div").html("I had my food!");
});
 
});
 
function eat(food, drink, callback)
{
	$("p").html("I ate "+food+" and had a "+drink);
 
	if(callback && typeof(callback) === "function" )
	{
		callback();
	}
 
}

Here we have a method called eat, which takes 3 parameters. First two are variable type and the 3rd parameter is a function type argument.

Once the page loads, we call eat method and pass pizza, cola and a callback method to it. After the first 2 variable values are displayed, eat method checks if the 3rd parameter is actually present and is a function – if so, it’ll call the function. So, the callback method is called after its preceding arguments are processed.

Anatomy and Working of Callback methods / anonymous functions


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=lIPOER59ZSY [Watch the Video In Full Screen.]



Examples:
1. If we have calls to Facebook API, Twitter API and Google Finance API’s: Using JavaScript(jQuery or nodejs) we could send the request to all these API’s concurrently and not worry much about its response time. Once any of these API’s respond, the corresponding callback methods are called. So while these scripts are executed, it binds the callback methods to its calls, and then stops worrying about its response!

2. Many ad networks have implemented asynchronous ad codes, since these codes use callback methods and there is no need for the webpage to wait until the ad server responds. If and when the ad server responds with an ad, the page or the ad spot is filled with the ad.

Auto-Refresh DIV using jQuery

Video tutorial illustrates auto-loading / refreshing of particular div content, using jQuery.

For the purpose of illustration, we’re also adding fadeOut and fadeIn effects to it.
You can safely remove those effects!

With fadeOut and fadeIn effects

1
$('#auto').fadeOut('slow').load('load.php').fadeIn('slow');

Without fadeOut and fadeIn effects

1
$('#auto').load('load.php');

HTML Page with DIVs

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>Auto-Refresh DIV</title>
</head>
<body>
<div id="one">One</div>
<div id="auto"></div>
<div id="three">Three</div>
 
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="my_script.js"></script>
</body>
</html>

This HTML document contains 3 div’s.
First and third div’s has some content which remains constant since the page has been loaded.
DIV with an id auto, is refreshed for every 2000 millisecond and the content is being loaded from load.php file.

load.php

1
Apple Inc

jQuery Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready( function(){
$('#auto').load('load.php');
refresh();
});
 
function refresh()
{
	setTimeout( function() {
	  $('#auto').fadeOut('slow').load('load.php').fadeIn('slow');
	  refresh();
	}, 2000);
}

we have added fadeOut and fadeIn effects for the purpose of demonstration, you can remove it if you want.
2000 is the time for Timeout call, in milliseconds.

Auto-Refresh Specific HTML Section: using jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=Ga3pOn7wXBA [Watch the Video In Full Screen.]



Output
Apple Inc

This will be useful for reloading a form or fetching fresh data from database.

jQuery Tutorial List

Follow the order in this post and make sure to practice all the tutorials and also share your knowledge with our awesome community on our official forum.

If you got to learn anything from our website, then please do not forget to share this page with your friends on Facebook, Google Plus, LinkedIn, Twitter etc..

1. jQuery Basics: Replace Text/String Inside HTML Document

2. jQuery: Selectors, Methods, Effects

3. callback methods / anonymous functions: jQuery

4. jQuery: Basic Image Effects

5. Animation of Text and Image: jQuery

6. Optimize / Improve Performance of jQuery Applications

7. Descendant Selectors: jQuery

8. Append/Add and Remove HTML/XML Elements: jQuery

9. Variables and Javascript Methods In jQuery

10. Animate Image with ‘this’ Selector: jQuery

11. jQuery Event Handling: Binding and Unbinding

12. Working With Images: Small jQuery Application

13. jQuery Methods and CSS: Restaurant Application

14. DOM Tree Traversal: jQuery

15. jQuery Filter Methods To Narrow Selection

16. Dynamically Load Images: jQuery Looping

17. Conditional Logic For Decision Making: jQuery

18. Detach and Attach DOM Elements: jQuery Array

19. Custom Functions: jQuery

20. Reading XML File Using jQuery AJAX Method

21. Insert Data Into MySQL: jQuery + AJAX + PHP

22. Objects, Arrays: JSON Using jQuery

23. Fetch JSON Data Using jQuery AJAX Method: getJSON

24. Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

25. Fetch/Extract Data From Database Without Refreshing Webpage: jQuery

26. Registration Form Using jQuery + PHP + AJAX (PART 1)

27. Registration Form Validation: PHP + jQuery + AJAX (PART 2)

28. Login Form: jQuery + PHP + AJAX

29. Dynamic Image Slider / Gallery: jQuery

30. Auto-Refresh DIV using jQuery

31. Dynamic Suggested List: jQuery .get() method

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$("#submit").click( function() {
 
	if( $("#username").val() == "" || $("#pass").val() == "" )
	  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
	else
	  $.post( $("#myForm").attr("action"),
	         $("#myForm :input").serializeArray(),
			 function(info) {
 
			   $("#ack").empty();
			   $("#ack").html(info);
				clear();
			 });
 
	$("#myForm").submit( function() {
	   return false;	
	});
});
 
function clear() {
 
	$("#myForm :input").each( function() {
	      $(this).val("");
	});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
< ?php
      include_once('db.php');
 
	  $username = mysql_real_escape_string( $_POST["username"] );
	  $password = mysql_real_escape_string( md5($_POST["pass"]) );
	  $fname = mysql_real_escape_string( $_POST["fname"] );
	  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
	  if( empty($username) || empty($password) )
	  {
	  	echo "Username and Password are mandatory - from PHP!";
		exit();
	  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
	  $row = mysql_fetch_row($res);
 
	  if( $row > 0 )
	    echo "Username $username has already been taken";
	  else
	  {
	   	  $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
	    if( mysql_query($sql) )
	     echo "Inserted Successfully";
	   else
	     echo "Insertion Failed";
	}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=dRk1r4SfSyA [Watch the Video In Full Screen.]



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.

Registration Form Using jQuery + PHP + AJAX (PART 1)

Video tutorial illustrates development of user registration form using jQuery AJAX method.
In this tutorial we shall build a registration form using which users can register without leaving the webpage. i.e., without being redirected to any other pages once he / she hits the submit/register button.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head><title>Registration Form: jQuery</title></head>
<body>
 
<form id="myForm" action="process.php" method="POST">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
<button id="submit">register</button>
</form>
 
<div id="ack"></div>
 
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a simple form with username, password, first name, last name fields and a button. Also a div with an id of ack where appropriate messages are displayed to the users.

Form has an id of myForm.
process.php file in the action field.
POST method.

PHP File: Database Connection Code
db.php

1
2
3
4
< ?php
      $conn = mysql_connect('localhost', 'root', '');
	  $db   = mysql_select_db('people');
?>

Here we’re connecting to the database called people.

Also Read: Connecting To MySQL server From PHP

Database Details:
Database Name: people
Table Name : users
Fields : slno, username, password, fname, lname.

PHP File: Inserting user entered data to database table
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
      include_once('db.php');
 
	  $username = mysql_real_escape_string( $_POST["username"] );
	  $password = mysql_real_escape_string( md5($_POST["pass"]) );
	  $fname = mysql_real_escape_string( $_POST["fname"] );
	  $lname = mysql_real_escape_string( $_POST["lname"] );
 
	  $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
	  if( mysql_query($sql) )
	   echo "Inserted Successfully";
	  else
	   echo "Insertion Failed";
?>

Here we use mysql_real_escape_string() method to avoid sql injection by the user.
We accept all the values entered by the user and store them in php variables.

Later we formulate MySQL query and pass these user entered values to it and execute it using mysql_query() PHP method.

Using the conditional logic statement we check if the query got executed or not. Then output appropriate message using echo.

This message will be retrieved by the call back function in jQuery and is being further processed as required.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
$("#submit").click( function() {
	 $.post( $("#myForm").attr("action"),
	         $("#myForm :input").serializeArray(),
			 function(info) {
 
			   $("#ack").empty();
			   $("#ack").html(info);
			 });
 
	$("#myForm").submit( function() {
	   return false;	
	});
});

Once the user clicks on the button with an id submit, we call $.post() method.
First parameter being the URL to which the data is being sent.
Second parameter is the actual data, which is being serialized using serializeArray() method of jQuery. It formats the user entered data into key => value pairs.
Third parameter, is the call back function.

Using the data returned by process.php we display the data in div tag with an id of ack.

We also disable the redirection of the webpage by returning false once the user clicks on the button.

jQuery File: Clearing the input fields
my_script.js

1
2
3
4
5
6
7
function clear() {
 
	$("#myForm :input").each( function() {
	      $(this).val("");
	});
 
}

It’s a custom function which selects all the input fields, loops through them and assigns an empty value.

jQuery File: Full / Final Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$("#submit").click( function() {
 
	 $.post( $("#myForm").attr("action"),
	         $("#myForm :input").serializeArray(),
			 function(info) {
 
			   $("#ack").empty();
			   $("#ack").html(info);
				clear();
			 });
 
	$("#myForm").submit( function() {
	   return false;	
	});
});
 
function clear() {
 
	$("#myForm :input").each( function() {
	      $(this).val("");
	});
 
}

Call clear() method after the user entered data is processed.

Registration Form Using jQuery + AJAX: PART 1


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=55FwdtnvQAM [Watch the Video In Full Screen.]



This way we turned our traditional registration form to a standard AJAX application form.

In tomorrows video tutorial lets see client side validation using jQuery and server side validation using PHP.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

Fetch/Extract Data From Database Without Refreshing Webpage: jQuery

Video tutorial illustrating, Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery + PHP + JSON + MySQL

You need not worry, even if you don’t know any one of these technology. Follow the tutorial, practice and understand, so that you could implement it for your applications.

Also read: Insert Data Into Database Without Refreshing Webpage.

In this tutorial we’ll be showing you, how to extract the data present in our MySQL database table without refreshing the webpage.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>Fetch/Extract Data From Database: jQuery + JSON + PHP+ AJAX</title>
</head>
<body>
<ul></ul>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a unordered list. We’ll fill it’s list items by extracting the data from the database, using jQuery and PHP.

PHP File: Database Connection Code
db.php

1
2
3
4
< ?php
      $conn = mysql_connect('localhost', 'root', '');
	  $db   = mysql_select_db('company');
?>

Here we’re connecting to the database called company.

Also Read: Connecting To MySQL server From PHP

PHP File: Extracting / Fetching Data From Database table and JSON Encoding
fetch.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< ?php
        include_once('db.php');
 
		$sql = "SELECT * FROM people";
		$res = mysql_query($sql);
		$result = array();
 
		while( $row = mysql_fetch_array($res) )
		    array_push($result, array('name' => $row[0],
			                          'age'  => $row[1],
						  'company' => $row[2]));
 
		echo json_encode(array("result" => $result));
?>

Here we connect to the database by including db.php file.
Next, select all the fields from the people table.
Extract data one-by-one and store it inside the array variable $result, with key => value pair (associative array).
Finally, using PHP standard function json_encode(), we encode the fetched data.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
function updates() {
	 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
	   $.each(data.result, function(){
	    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
	   });
 });
}

Using the jQuery AJAX method’s shortcut, $.getJSON() method, we parse fetch.php and process the data passed to the callback function.

We empty the unordered list to avoid duplicate entries later on.

Now loop through all the objects present in the jSON output of fetch.php
Using it’s key, retrieve it’s respective values and append it to the unordered list, as it’s list items.

jQuery File: AJAXing
my_script.js

1
2
3
4
5
6
function done() {
	  setTimeout( function() { 
	  updates(); 
	  done();
	  }, 200);
}

Call updates() function and itself[ done() ] inside setTimeout() function with a time gap of 200 milliseconds.

jQuery File: Full/Final Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready( function() {
 done();
});
 
function done() {
	  setTimeout( function() { 
	  updates(); 
	  done();
	  }, 200);
}
 
function updates() {
	 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
	   $.each(data.result, function(){
	    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
	   });
 });
}

Call done() once the document is loaded.
You could also call done() function once the window is focused or once some button is clicked or any other user events. This would reduce the database calls considerably.

Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=G_7oYeNU_3g [Watch the Video In Full Screen.]



This would highly enhance the user experience and would help in building rich web applications which look more like desktop / standalone applications.

Please share this video with your friends and also LIKE it on social network sites and on YouTube. Thanks you <3

Related Read:
Insert Data Into Database Without Refreshing Webpage

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

Video tutorial illustrates the extraction of JSON Array elements using jQuery AJAX method: getJSON

Here we extract data(JSON ARRAY) from an external JSON file, which has a file extension .json

HTML code
index.html

1
2
3
4
5
6
7
8
<html>
<head><title>Fetch JSON array Data</title></head>
<body>
<ul></ul>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a unordered list. We’ll be filling it’s list items from the JSON file using jQuery.

JSON File
json_data.json

1
2
3
4
5
6
{
 "person": [  
     { "name": "Satish", "age": 25 },
     { "name": "Shwetha", "age": 24 }
 ]
}

Here we have a key called “person”, which is a JSON array.
“person” has two elements in it, which are objects.
Each object has two key => value pairs.
The key being, name and age.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
 $.getJSON("json_data.json", function(data){
       $.each(data.person, function(){
	         $("ul").append("<li>Name: "+this['name']+"</li>
                                <li>Age: "+this['age']+"</li>
                                <br />");
	   });
 });

Once the document loads, we call an anonymous function. Inside that, we call the shortcut function of jQuery AJAX method i.e., $.getJSON method.
The first parameter is the file to be parsed, second parameter is the callback function.

Inside the callback function, we loop through the array elements and fetch the values using its key names, and finally append it to the unordered list of index.html

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=VAMz-fcDNhs [Watch the Video In Full Screen.]



To make the AJAX effect, you could write the jQuery coding inside a custom function and then call it for setTimeout() function etc:
setTimeout(customFunction, 4000);
setInterval(repeatFunctionCall, 4000);
slideDown().delay(4000).slideUp(); ( Chain method )

Fetch JSON Data Using jQuery AJAX Method: getJSON

Video tutorial illustrates fetching of JSON data using jQuery AJAX method, getJSON
Since its an AJAX method, the data is fetched without the need for refresh of the browser.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head><title>JSON jQuery AJAX</title></head>
<body>
 
<ul></ul>
 
<button>Users</button>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have a unordered list, without any list items in it. We’ll be fetching the list items from the JSON file using jQuery.
A button, clicking upon which we would fetch the Data inside jSON file.

JSON File
json_data.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
   "p1": { 
           "name": "Satish",
		          "age":   25,
		          "company": "Techntoip"
         },
 
 
   "p2": {
           "name": "Kiran",
		          "age":   28,
		          "company": "Oracle"   
         }			 		 		 
}

Starts with a opening brace and ends with a opening brace.
In our example, we have taken two objects.
p1 and p2 are keys. It’s values are present inside opening and closing brace.
Each object has name, age and company info.

Also watch: Objects, Arrays: JSON Using jQuery.

jQuery Code
my_script.js

1
2
3
4
5
6
7
$("button").click( function() {
 $.getJSON( "json_data.json", function(obj) { 
  $.each(obj, function(key, value) { 
         $("ul").append("<li>"+value.name+"</li>");
  });
 });
});

Once the user clicks on the button, we invoke $.getJSON method.
First parameter we are passing is the URL of the json file. Next the call back function.

The call back function receives the jSON data which we have called as obj in our example.
Using $.each() method we iterate through all the objects present in our json file and then split them into key => value pair.

Now using the value we fetch the name present inside each objects value.

Video Tutorial: Fetch JSON Data Using jQuery AJAX Method: getJSON


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=pe6keTE9LbE [Watch the Video In Full Screen.]




jSON & Database
We can generate jSON data out of a database and then fetch it using jQuery and display it on our web browser without the need for the modification of any code.
Whenever the json file or the database table data gets updated/modified, it instantly reflects on our web application.

Note:
You must open the file from a server. localhost works file too.
If you access the files directly from your computer folder, this application doesn’t work. So the files MUST be on a server.

Objects, Arrays: JSON Using jQuery

Video tutorial illustrates the basics of JSON: Create Object, Arrays, Access Elements, Modify/Update the value etc.

JSON full form: JavaScript Object Notation.

JSON is a lightweight data-interchange format.
It’s easy for humans to read and write.
It’s easy for machines to parse and generate.
So it’s more efficient at transferring data than XML.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head><title>JSON and jQuery!</title></head>
<body>
 
<ul></ul>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

We have a simple HTML structure, with a unorder list.
We’ll fill the list items from the JSON data using jQuery.

JSON and jQuery
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready( function() {
 
 var v1 = { "name": "Satish", "age": 25, "company": "Technotip IT Solutions" };
 var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
 
 var obj = { "obj1": v1, "obj2": v2	};
 
 var v3 = { "companies": [ "Microsoft", "Apple", "Google", "Oracle" ] };
 
  $("ul").append("<li>"+obj["obj1"]["name"]+"</li>");
  $("ul").append("<li>"+v3.companies[0]+"</li>");
});

Object
An object is a set of name/value pairs. An object begins with { and ends with }. Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

Array
An array is an ordered collection of values. An array begins with [ and ends with ]. Values are separated by , (comma).
Values in JSON can be string, number, array, objects, Boolean values or even null.

Fetch JSon Data From Object:
Object_name.Key;

Fetch JSon Data From Array:
Object_name.array_name[index_number];

Update JSON Data:

JSON and jQuery
my_script.js

1
2
3
4
5
 var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
  $("ul").append("<li>"+v2.company+"</li>");
 
 v2.company = "Apple";
  $("ul").append("<li>"+v2.company+"</li>");

Would output
Oracle
Apple

Similarly, we could change the value of any key of an object or an array element.

Video Tutorial: Objects, Arrays: JSON Using jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=MK39DQabaW8 [Watch the Video In Full Screen.]



We could nest objects inside objects or arrays inside objects or objects inside an array etc, upto any level of complexities.
This is advantages for web applications like building menus with nested items, which are fetched from database.

Since, writing and fetching and parsing of JSON data is easy, most developers have stared using JSON over XML.