The Wayback Machine - https://web.archive.org/web/20240602004802/https://www.geeksforgeeks.org/how-to-make-a-json-call-using-jquery/
Open In App

How to make a JSON call using jQuery ?

Last Updated : 26 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Use the getJSON() function in jQuery to load JSON data. The getJSON() function uses a GET HTTP request to retrieve JSON-encoded data from the server. In this article, we will learn about the jQuery getJSON() function and its implementation through examples.

Syntax:

$(selector).getJSON(url, data, success(data, status, xhr))

Parameters: This method accepts three arguments, which are listed below:

  • url: The argument URL is necessary. It is used to indicate the URL as a string to which the request is sent.
  • data: It is a parameter that is optional and indicates the data that will be transmitted to the server.
  • callback: It is also an optional argument that is executed if the request is successful.

Return Value: It gives back an XMLHttpRequest object.

Example 1: In this example, we use the getJSON() function to retrieve JSON data from an external JSON file. There is an external JSON file entitled emp.json that holds an employee’s information. 

The URL and the callback function are two arguments of the getJSON() method that we are utilizing. It fetches JSON-encoded data from the server using a GET HTTP request. The URL parameter has been set to emp.json. The callback function has two parameters data and status. The first argument contains the contents of the requested page, while the second contains the request status. The data load from the server is visible in the output, and the request status is a success.

To retrieve the data from the external JSON file, we have to click the given button.

emp.json:

{
    "name": "Vishal Kumar", 
    "age" : "22", 
    "gender": "Male",
    "salary": 56000 
}

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <style>
        body {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
  
        #output {
            background-color: #ecf721;
        }
    </style>
  
    <script>
        $(document).ready(function () {
            $("#btn").click(function (event) {
                $.getJSON("emp.json", function (emp) {
                    $("#output").html("<p> Name: " 
                        + emp.name + "</p>");
                    $("#output").append("<p>Age : " 
                        + emp.age + "</p>");
                    $("#output").append("<p>Gender: " 
                        + emp.gender + "</p>");
                    $("#output").append("<p>Salary: " 
                        + emp.salary + "</p>");
                });
            });
        });
    </script>
</head>
  
<body>
    <h2 style="color:green;">
        GeeksforGeeks
    </h2>
  
    <p>
        Click on the button to load 
        data from emp.json file
    </p>
  
    <div id="output"></div>
  
    <input type="button" id="btn" 
        value="Get Employee Data" />
</body>
  
</html>


Output:

 

Example 2: The following example uses the getJSON() method to load the random quotes from Formastic API. 

Whenever the user clicks on the given button a request to the API server is made. On successfully receiving data from the server it goes to the done interface which contains a callback function having one parameter called quote. This parameter holds the data of the requested page.

If there is an error in receiving the data, then it goes to the fail callback function having one parameter called err. This parameter holds the error message returned by a server which you can log and try to solve.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  
    <style>
        body {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
  
        #quote {
            background-color: #25bf1a;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green;">
        GeeksforGeeks
    </h2>
      
    <p>Click on the button to call API</p>
      
    <div id="quote"></div>
      
    <input type="button" id="btn" value="Call API" />
  
    <script>
        $(document).ready(function () {
            var forismaticAPI =
"http:.../api/1.0/?method=getQuote⟨=en&format;=jsonp&jsonp;=?";
            $("#btn").click(function () {
                $.getJSON(forismaticAPI)
                    .done(function (quote) {
                        $("#quote").html("<p> quoteText: " 
                            + quote.quoteText + "</p>");
                        $("#quote").append("<p>quoteAuthor : "
                            + quote.quoteAuthor + "</p>"
                        );
                        $("#quote").append("<p>senderName: " 
                            + quote.senderName + "</p>");
                        $("#quote").append("<p>senderLink: " 
                            + quote.senderLink + "</p>");
                        $("#quote").append("<p>quoteLink: " 
                            + quote.quoteLink + "</p>");
                    })
                    .fail(function (err) {
                        console.log(err);
                    });
            });
        });
    </script>
</body>
  
</html>


Output:

 



Similar Reads

Program to swap two integer parameters using call by value & call by address in PHP ?
Call by value: In call by value, we will send the value from the calling function to the called function. The values of the calling function arguments are directly copied to the corresponding arguments of the called function. If any modification is done on the arguments of the called function, it will not be effected on the arguments of the calling
3 min read
Call by Value Vs Call by Reference in JavaScript
Call by Value: In this method, values of actual parameters are copied to the function’s formal parameters, and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. Suppose there is a variable named “a”. Now, we store a primitive value(boo
3 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to call a function automatically after waiting for some time using jQuery?
In order to run a function automatically after waiting for some time, we are using the jQuery delay() method. The .delay() method in jQuery which is used to set a timer to delay the execution of the next item in the queue.Syntax: $(selector).delay(para1, para2); Approach: When the Button is clicked the process is delayed to the specific time period
2 min read
How to call a function when content of a div changes using jQuery ?
The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up. .change(): This method will only trigger when some change occurs in the element or field. It accepts an option
2 min read
How to make a call-able link using HTML ?
With the rise of mobile web surfing the benefits of calling directly from a web page have become more realistic. Making a call-able link is easy with the use of HTML. HTML provides browsers with protocols such as tel which are used to add clickable phone numbers. Every browser responds differently to these protocols. Some launch the phone app with
2 min read
How to make GET call to an API using Axios in JavaScript?
Axios is a promise-based HTTP client designed for Node.js and browser. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. The following scrip
2 min read
How to make POST call to an API using Axios.js in JavaScript ?
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript or with any library accordingly. The following scri
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read