How to use jQuery getJSON() method for AJAX to get JSON data

jQuery getJSON() method

As explained in the previous chapter, the jQuery get() method is used to load data using HTTP get request method. The getJSON() method of jQuery is specifically used to load JSON data by using the HTTP GET request.

The JSON, acronym for JavaScript Object Notation, is a lightweight data-interchange format, used to store and exchange text information.

A running example of jQuery getJSON

See example online with data loaded from getJSON.json file

How to use the getJSON method?

This is how you may use the getJSON method:

$.getJSON( url, [data], success_function( data, Status, xhr ))

Where:

URL:  is a string specifying the server to which request is sent. This is required parameter.

data: Data to be sent to the server along with HTTP request

success: Optional parameter. If a request is successful this function will execute if given. It also contains returned data from the server. The other parameters in this call function are:

success_function(data, status, xhr)

Where:

  1. Data = returned data from server
  2. Status = returns request status i.e. success, error, timeout, notmodified
  3. xhr= it contains XMLHttpRequest object.

A live demo of getJSON jQuery

The example below shows how to load text data from JSON file, namely getjson.json. Place this file at the same location where you are calling getJSON() method. The data loaded after clicking the button is shown in paragraphs.

jQuery getJSON

Experience this example online

First getjson.json file:



HTML file code:



Experience this example online

Useful reading: jQuery Get() method | jQuery post method


Was this article helpful?

Related Articles

Leave A Comment?