Using jQuery getJSON() Method

I already discussed how to Get Data from External File with jQuery Ajax Method before. Actually there is a much easier way to get data from external file (usually JSON file format). This is called getJSON() method. You may consider the getJSON() method a simplified format of Ajax Method.

In brief, the getJSON() method is used to get JSON data using an AJAX HTTP GET request. Okay! I will illustrate how the getJSON() method works with some simple examples.

Example 1

Let’s start with a most simple and basic example.

The webpage has a button. When the submit button is clicked, it will get the data from an external file (member.json) with JSON file format. The data of the external JSON file will display in the grey DIV layer.

Here’s the codes of the webpage:

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery getJSON() Method</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#myForm").submit(function(){
                    return false;
                });

                $('#btnSubmit').click(function(event) {

                    // The getJSON() method is used to get JSON data (member.json)
                    //  using an AJAX HTTP GET request.
                    $.getJSON('member.json', function(data) {

                         // Callback
                        // // Display the JSON data in outputBox DIV layer
                        $('#outputBox').text('Member Name: ' + data.firstName + ' ' + data.lastName);

                      });

                });    
            });
        </script>
</head>
<body> 

<h1>Using jQuery getJSON() Method</h2>

<div id="container">

    <strong>Member Area</strong>

    <form id="myForm" name="myForm" >        
    <button type="submit" name="btnSubmit" id="btnSubmit">Submit</button>            
    </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

Here’s the content of external JSON file (member.json).

 
{
    "firstName": "Peter",
    "lastName": "Pan"
}

What is JSON file format?

JSON file format is actually similar to XML. It simply uses to store text data or text information. You may consider JSON as a text database. JSON is lighter than XML, and much easier and faster to parse.

When the Submit button is clicked, the values of firstName and lastName of the JSON file will be displayed. Very simple and easy. Isn’t it?

Download:
Please click here to download jQuery getJSON Example 1.

Example 2

In example 1, the JSON file (member.json) has only one record.

 
{
    "firstName": "Peter",
    "lastName": "Pan"
}

Actually, a JSON file usually has a lot of records. Let’s increase the member.json JSON file to two records:

[
    {
        "firstName": "Peter",
        "lastName": "Pan"
    },
    {
        "firstName": "Paul",
        "lastName": "Anka"
    }
]

Since the data sent back to the webpage is in a string. We need to loops through the data string to retrieve individual value. A simple and easy way to do that is using the each() method. The codes of the webpage becomes:

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery getJSON() Method</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#myForm").submit(function(){
                    return false;
                });

                $('#btnSubmit').click(function(event) {

                    // The getJSON() method is used to get JSON data (member.json)
                    //  using an AJAX HTTP GET request.
                    $.getJSON('member.json', function(data) {

                        var items = [];

                         $.each(data, function(key, val){           
                                items.push("First Name : ", val.firstName, ", ",
                              "Last Name : ", val.lastName, "<br>");
                        });

                         // Callback
                        // // Display the JSON data in outputBox DIV layer
                        $('#outputBox').html(items.join(''));

                      });

                });    
            });
        </script>
</head>
<body>

<h1>Using jQuery getJSON() Method</h2>

<div id="container">

    <strong>Member Area</strong>

    <form id="myForm" name="myForm" >        
    <button type="submit" name="btnSubmit" id="btnSubmit">Submit</button>            
    </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

When the Submit button is clicked, the values of firstName and lastName of the JSON file will be displayed.

Download:
Please click here to download jQuery getJSON Example 2.

Example 3: Get External CSV Data

There are many useful information or data (for example: financial data, weather data, etc…) hosting on the Internet. The current data file format is usually CSV. Therefore, in many situation, we need to get the data from other sources, and then convert the data into a JSON file format for using in our webpage. Let’s take PHP as an example. PHP can easily convert the csv file format into a JSON file format. Actually this is same for other computer languages.

The process can be illustrated in the following diagram:

I am still using example 2 for this illustration, with just some minor modification.

External CSV Data File

Firstly, let’s see the contents of the CSV file (table.csv). This is the stock history of a stock. In a real working application, this CSV file should be getting from the stock server, rather than a local file.

Date,Open,Close
2013-10-07,84.50,84.50
2013-10-04,84.00,84.50
2013-10-03,84.25,84.65
2013-10-02,84.80,85.10
2013-10-01,84.35,84.35

Webpage

The codes the webpage is almost the same as example 2, except that the keys and values are different:

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery getJSON() Method</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#myForm").submit(function(){
                    return false;
                });

                $('#btnSubmit').click(function(event) {

                    // Use getJSON() method getting JSON data through csv_to_json.php file
                    //  using an AJAX HTTP GET request.
                    $.getJSON('csv_to_json.php', function(data) {

                        var items = [];

                         $.each(data, function(key, val){           
                                items.push("Date : ", val.Date, ", ",
                              "Open Price: ", val.Open, ", ",
                            "Close Price: ", val.Close, "<br>");
                        });

                         // Callback
                        // // Display the JSON data in outputBox DIV layer
                        $('#outputBox').html(items.join(''));

                      });

                });    
            });
        </script>
</head>
<body> 

<h1>Using jQuery getJSON() Method 3</h2>

<div id="container">

    <strong>Member Area</strong>

    <form id="myForm" name="myForm" >        
    <button type="submit" name="btnSubmit" id="btnSubmit">Submit</button>            
    </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

PHP File

Then we need the PHP file to fetch the data from the external file. And then convert the data into JSON file format.

The PHP codes in this example is from GitHub, and written by me. Actually there are many similar codes on the Internet. Just modify them to use for your projects rather than starting from scratch.

<?php
/*
* Converts CSV to JSON
* Example uses Google Spreadsheet CSV feed
* csvToArray function I think I found on php.net
* https://gist.github.com/robflaherty/1185299
*/

header('Content-type: application/json');

// Set your CSV feed if the file is hosting on other server.
//  This is usually the case in a real application.
// $feed = 'https://www.serverPath.com';
$feed = 'table.csv';

// Arrays we'll use later
$keys = array();
$newArray = array();

// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}

// Do it
$data = csvToArray($feed, ',');

// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);

foreach ($labels as $label) {
$keys[] = $label;
}

// Add Ids, just in case we want them later
$keys[] = 'id';

for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}

// Print it out as JSON
echo json_encode($newArray);

?>

When the Submit button is clicked, the values of the stock data will be displayed.

Note:
I am quite sure that most file format on the Internet will be changed from csv to JSON file format in the very near future.

Download:
Please click here to download jQuery getJSON Example 3.

Example 4: Pass a Variable Along With getJSON() Method

We already learned a lot how to use jQuery getJSON() method. Let’s discuss a even more interesting example. The work flow of this example is illustrated in the following diagram:

A user enter information in a web form, click on the submit button. Then the user data is post to the next webpage. The next webpage then pass the user data using the getJSON() Method to a PHP file for processing. Finally the user data is pass back to the webpage in a JSON file format.

The codes are actually very similar to example 3 with just a little modification.

Here’s the codes of the main Webpage:

<?php
    // This variable should be sent from a web form, e.g.
    // $myName = $_POST["name"];
    $myName = "alex";
?>

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery getJSON() Method With Passing Variable</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){

                    // Use getJSON() method getting JSON data through passVariable.php file
                    //  using an AJAX HTTP GET request.
                    // A variable ($myName) is also passing to the PHP file
                    $.getJSON('passVariable.php', { id: '<?php echo $myName; ?>' }, function(data) {

                         // Callback
                        // // Display the JSON data in outputBox DIV layer
                        $('#outputBox').html("My name is: " + data);

                      });

            });
        </script>
</head>
<body> 

<h1>Using jQuery getJSON() Method 4</h2>

<div id="container">

    <strong>Member Area</strong>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

For simplicity, the codes of the web form is ignored. The $myName variable should be posted from the web form:

<?php
    // This variable should be sent from a web form, e.g.
    // $myName = $_POST["name"];
    $myName = "alex";
?>

Passing variable(s) along with getJSON() method is very simple:

$.getJSON('passVariable.php', { id: '<?php echo $myName; ?>' }, function(data) {

                         // Callback
                        ........... codes here .............

                      });

Here’s the codes of the PHP file:

<?php

// Get the value of $id variable
// This $id variable is along with getJSON() method
$id = $_GET['id'];

// Print it out as JSON
echo json_encode($id);

?>

The result will be:

Download:
Please click here to download jQuery getJSON Example 4.

Here’s another example using the HTTP GET method to process the web form.

Please click here to download jQuery getJSON Example 4-1.

Example 5: Pass Multiple Variables Along With getJSON() Method

In a real application, there should be more than one variables that need to send with jQuery getJSON() method. The codes are almost the same, with just a minor modification.

Here’s the codes of the main webpage:

<?php
    // This variable should be sent from a web form, e.g.
    // $myName = $_POST["name"];
    // $age = $_POST["age"];
    $myName = "alex";
    $age = 20;
?>

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery getJSON() Method With Passing Multiple Variable</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){

                    // Use getJSON() method getting JSON data through passVariable.php file
                    //  using an AJAX HTTP GET request.
                    // A variable ($myName) is also passing to the PHP file
                    $.getJSON('passVariable.php', { id: '<?php echo $myName; ?>', age: '<?php echo $age; ?>' }, function(data) {

                         // Callback
                        // // Display the JSON data in outputBox DIV layer
                        $('#outputBox').html("My name is: " + data.member[0] + "<br>" + "My age is: " + data.member[1]);

                      });

            });
        </script>
</head>
<body> 

<h1>Using jQuery getJSON() Method 5</h2>

<div id="container">

    <strong>Member Area</strong>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

As you can see, passing multiple variables with getJSON() method is very simple:

$.getJSON('passVariable.php', { id: '<?php echo $myName; ?>', age: '<?php echo $age; ?>' }, function(data) {

                         // Callback
                        ............ codes here .......

                      });

Here’s how PHP file process the data:

<?php

// Get the value of $id variable
// This $id and $age variable are along with getJSON() method
$id = $_GET['id'];
$age = $_GET['age'];

// Pack the data into an array
$data = array();
$data['member'] = array($id, $age);

// Print it out as JSON
echo json_encode($data);

?>

Then we can access the data with reference to the index of the array, for example:

data.member[0]
data.member[1]

The result will now be:

Download:
Please click here to download jQuery getJSON Example 5.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>