Select Your Favourite
Category And Start Learning.

How to Get JSON Data with jQuery | jQuery.getJSON() Method

There are plenty of ways to load JSON-encoded data. One of the popular ways is by using ajax. But what if Ajax is not working? Is there an alternative?

If you are using jQuery, you may use getJSON() method as an alternative for ajax().

What is getJSON?

getJSON() is a method in jQuery that fetches JSON-encoded data from the server using GET HTTP request. Unlike Ajax, getJSON only accepts three parameters and return an XMLHttpRequest object once the process is a success.

Syntax

jQuery.getJSON( url [, data ] [, success ] )
Code language: JavaScript (javascript)
url
Data type: string
Value: the URL to which the request is sent.
data
Data Type: object or string
Value: An object that is sent to the server with the request.
success
For this parameter, you can use a function to trigger once the getJSON method is a success.

getJSON can also be converted into AJAX.

If you are familiar with AJAX, this is how getJSON will look like in AJAX:

$.ajax({ url: url, data: data, dataType: "json", success: function(data) {} });
Code language: JavaScript (javascript)

Since getJSON will process through GET HTTP request, all data that you will send to the server will be automatically converted into a url-encoded data and add to the URL as a query string.

For example

$.getJSON({ url: 'https://google.com', { name: "John" } });
Code language: JavaScript (javascript)

The full URL will look something like this

https://google.com/?name=John
Code language: JavaScript (javascript)

Pros

  • Simple and easy to use
  • Understandable and easy to read

Cons

  • No speed difference from ajax
  • Unsecured especially if you’re passing sensitive data

Example

To make getJSON work, you have to create an external JSON file and link it to the getJSON method otherwise your code will not work.

Use the following source code as your reference.

person_data.json

{ "id": 1, "name": "John", "company": "WeeklyHow", "position": "Content Writer" }
Code language: JSON / JSON with Comments (json)

If you want to add more data in your json file, just follow its syntax.

"variable": "value"
Code language: JavaScript (javascript)

It’s important to remember that each data ends with a comma (,) except the last data.

index.html

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id = "output" style = "background-color:#39B54A;"></div> <input type = "button" class="getData" value = "Get Data" /> <!-- Get JSON data when button is clicked --> <script type = "text/javascript" language="javascript"> $(document).ready(function() { $(".getData").click(function(event){ $.getJSON('https://weeklyhow.com/codes/examples/json/person_data.json', function(data) { $('#output').html('<p> ID: ' + data.id + '</p>'); $('#output').append('<p>Name: ' + data.name + '</p>'); $('#output').append('<p> Company: ' + data.company + '</p>'); $('#output').append('<p> Role: ' + data.position + '</p>'); }); }); }); </script> </body> </html>
Code language: HTML, XML (xml)

Demo

The example source code above will display the following output. (Though we have added a little styling for the sake of the good display).

You may try to press the button to see the result.

Oh no! I’m empty. Please click the button.

Good job! You can now get data from JSON files.

Now, what if the data don’t exist?

What if getJSON() method failed to process?

There’s another method that you can use to check if getJSON() method fails to process and that is .fail() method.

See the following example below.

$.getJSON( "https://weeklyhow.com/codes/examples/json/file_dont_exist.json", function(data) {}) .fail(function( jqxhr, status, error ) { var er = status + ", " + error; alert( "Request Failed: " + er ); });
Code language: JavaScript (javascript)

The above example will prompt an output saying that the request failed with additional information as to why the process failed.

This is a great way to double-check or to understand what’s going on with your getJSON method.

Conclusion

There are many ways to get data from requests. getJSON method is one of them. If you’re sending data that are sensitive, we highly encourage you to use $.ajax() instead to ensure that your data is safe from public view.

Leave a comment

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