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



YouTube Link: https://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.

2 thoughts on “Fetch JSON Data Using jQuery AJAX Method: getJSON”

  1. Thanks for the excellent tutorial, you did a great job of showing how simple it is to implement and how powerful it can be in future projects.

Leave a Reply

Your email address will not be published. Required fields are marked *