Paramclasses Academy - Blog

Tutorials Details

←
Post 12 of 15
→

How to Use jQuery with JSON and APIs?

How to Use jQuery with JSON and APIs?

October 14, 2026

How to Use jQuery with JSON and APIs? A Complete Tutorial with Examples

Introduction

Modern websites often need to communicate with APIs to retrieve or send information. For example, an application might load product details, display weather information, retrieve user records, or show blog posts without reloading the entire webpage.

To work with this data, developers commonly use APIs, JSON, and AJAX.

  • API: A way for software systems to communicate with each other.

  • JSON: A lightweight text format used to exchange structured data.

  • jQuery: A JavaScript library that makes common tasks, including HTTP requests and DOM manipulation, easier.

In this tutorial, you will learn how to use jQuery to request API data, process JSON responses, display the results in HTML, and handle errors.

1. What Is JSON?

JSON stands for JavaScript Object Notation. It is a text-based format for storing and exchanging structured data.

JSON represents information using objects, arrays, strings, numbers, booleans, and null.

Example of JSON Data

{
    "id": 1,
    "name": "Rahul",
    "role": "Web Developer",
    "active": true
}

This JSON object contains four properties:

  • id: a number.

  • name: a string.

  • role: a string.

  • active: a boolean.

JSON is commonly used in API responses because it is readable and supported by many programming languages.

JSON Array Example

[
    {
        "id": 1,
        "name": "Rahul"
    },
    {
        "id": 2,
        "name": "Priya"
    },
    {
        "id": 3,
        "name": "Amit"
    }
]

This example contains an array of three objects. Each object represents a user.

2. What Is an API?

API stands for Application Programming Interface.

An API allows one application to request information or functionality from another application.

For example, a website might request a list of blog posts from a server through an API endpoint.

A typical API request and response work like this:

  1. The browser sends an HTTP request to an API endpoint.

  2. The server receives and processes the request.

  3. The server returns a response, often in JSON format.

  4. jQuery receives the response.

  5. JavaScript uses the response to update the webpage.

A URL such as /api/products might be an endpoint in your own application. The exact URL depends on how the API is designed.

3. How Do jQuery, JSON, and APIs Work Together?

These technologies have different roles.

Technology Main purpose
jQuery Sends requests and updates webpage elements.
JSON Represents structured data exchanged between systems.
API Defines how an application can request or submit data.
AJAX Allows asynchronous HTTP communication without a full-page reload.

For example, jQuery can request a list of products from an API. The API returns JSON, and jQuery displays each product on the webpage.

4. How to Use $.getJSON() in jQuery

The $.getJSON() method sends an HTTP GET request and expects a JSON response.

Syntax

$.getJSON(url, function (data) {
    // Process the JSON response
});

Here:

  • url is the API endpoint.

  • data contains the parsed response.

Simple Example

We will use a public demo API that returns sample posts.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery JSON Example</title>
</head>
<body>

    <h1>API Post</h1>
    <button id="loadPost">Load Post</button>
    <div id="result"></div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $("#loadPost").on("click", function () {
            $.getJSON(
                "https://jsonplaceholder.typicode.com/posts/1"
            )
            .done(function (data) {
                $("#result").html(
                    "<h2></h2><p></p>"
                );

                $("#result h2").text(data.title);
                $("#result p").text(data.body);
            })
            .fail(function () {
                $("#result").text("Unable to load the post.");
            });
        });
    </script>

</body>
</html>

Expected Output

When the user clicks Load Post, the page displays the title and body of the sample post returned by the API.

This example requires an internet connection. The public endpoint is intended for testing and demonstration, not production data.

Code Explanation

Step 1: Add a button

<button id="loadPost">Load Post</button>

The button lets the user start the API request.

Step 2: Make the request

$.getJSON("https://jsonplaceholder.typicode.com/posts/1")

This requests a JSON response from the demo API.

Step 3: Read the response

$("#result h2").text(data.title);
$("#result p").text(data.body);

The data.title and data.body properties provide values from the returned JSON object.

Step 4: Handle errors

.fail(function () {
    $("#result").text("Unable to load the post.");
});

If the request fails, the user sees an error message.

Using .text() for API-provided text helps prevent it from being interpreted as HTML.

5. How to Display Multiple JSON Records in HTML

Many APIs return arrays containing multiple records. You can use jQuery's $.each() method to loop through those records.

Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Display API Data with jQuery</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 850px;
            margin: 30px auto;
            padding: 16px;
            background: #f4f7fb;
        }

        h1 {
            color: #174ea6;
        }

        .post {
            background: white;
            padding: 16px;
            margin-bottom: 12px;
            border-radius: 8px;
            border: 1px solid #dce3ee;
        }

        button {
            padding: 10px 16px;
            background: #174ea6;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        #message {
            margin: 16px 0;
        }
    </style>
</head>
<body>

    <h1>Blog Posts</h1>

    <button id="loadPosts">Load Posts</button>

    <p id="message" role="status" aria-live="polite"></p>
    <div id="posts"></div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $("#loadPosts").on("click", function () {
            const button = $(this);

            button.prop("disabled", true);
            $("#message").text("Loading posts...");
            $("#posts").empty();

            $.getJSON("https://jsonplaceholder.typicode.com/posts?_limit=5")
                .done(function (posts) {
                    if (!Array.isArray(posts) || posts.length === 0) {
                        $("#message").text("No posts found.");
                        return;
                    }

                    $.each(posts, function (index, post) {
                        const card = $("<article>", {
                            class: "post"
                        });

                        $("<h2>")
                            .text(post.title)
                            .appendTo(card);

                        $("<p>")
                            .text(post.body)
                            .appendTo(card);

                        $("#posts").append(card);
                    });

                    $("#message").text("Posts loaded successfully.");
                })
                .fail(function () {
                    $("#message").text(
                        "Unable to load posts. Please try again."
                    );
                })
                .always(function () {
                    button.prop("disabled", false);
                });
        });
    </script>

</body>
</html>

How This Example Works

  1. The user clicks Load Posts.

  2. jQuery requests five sample posts from the API.

  3. The response is received as an array of objects.

  4. $.each() loops through the posts.

  5. jQuery creates an article element for each post.

  6. The title and body are inserted as text.

  7. A status message informs the user whether the request succeeded or failed.

This example demonstrates how to display multiple API records dynamically.

6. How to Use $.ajax() with JSON

The $.ajax() method gives you more control over the request, including its HTTP method, expected response format, and error handling.

Example

$.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    method: "GET",
    dataType: "json",

    success: function (data) {
        console.log("Post title:", data.title);
        console.log("Post body:", data.body);
    },

    error: function (xhr, status, error) {
        console.error("Request failed:", status, error);
    }
});

Explanation

  • url specifies the endpoint.

  • method: "GET" requests data.

  • dataType: "json" tells jQuery to expect a JSON response.

  • success processes a successful response.

  • error handles a failed request.

Use $.getJSON() for simple JSON GET requests. Use $.ajax() when you need more configuration.

7. How to Send JSON Data to an API

Sometimes you need to send information to an API rather than retrieve it.

For example, an application might submit a new post to a server.

When an API expects a JSON request body, you can use JSON.stringify() to convert a JavaScript object into a JSON string.

Example

const newPost = {
    title: "Learning jQuery",
    body: "This is a sample post.",
    userId: 1
};

$.ajax({
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "POST",
    contentType: "application/json; charset=UTF-8",
    dataType: "json",
    data: JSON.stringify(newPost),

    success: function (response) {
        console.log("Response received:", response);
    },

    error: function (xhr, status, error) {
        console.error("Request failed:", status, error);
    }
});

Important Points

contentType specifies the format of the request body being sent to the server.

dataType specifies the response format that jQuery expects.

JSON.stringify() converts a JavaScript object into a JSON string.

The demo API may return a simulated created record, but it does not permanently save the new post. For a real application, use an API that supports creating records and verify its validation, authentication, and response behavior.

8. What Is the Difference Between JSON.parse() and JSON.stringify()?

Both methods work with JSON, but they perform opposite conversions.

Method Purpose
JSON.parse() Converts a valid JSON string into a JavaScript value.
JSON.stringify() Converts a JavaScript value into a JSON string.

Example: JSON.parse()

const jsonString = '{"name":"Rahul","role":"Developer"}';

const user = JSON.parse(jsonString);

console.log(user.name);
console.log(user.role);

Output:

Rahul
Developer

Example: JSON.stringify()

const user = {
    name: "Rahul",
    role: "Developer"
};

const jsonString = JSON.stringify(user);

console.log(jsonString);

Output:

{"name":"Rahul","role":"Developer"}

When jQuery receives a valid JSON response and dataType: "json" is configured, it parses the response automatically. You generally do not need to call JSON.parse() again.

9. How to Handle API Errors

API requests can fail for several reasons:

  • The internet connection is unavailable.

  • The server returns an HTTP error.

  • The endpoint URL is incorrect.

  • The API requires authentication.

  • The response does not match the expected format.

  • The browser blocks a cross-origin request because of CORS restrictions.

Use .fail() or the error callback to handle failures.

$.getJSON("/api/products")
    .done(function (products) {
        console.log("Products received:", products);
    })
    .fail(function (xhr, status, error) {
        console.error("Status:", status);
        console.error("Error:", error);
        console.error("HTTP status code:", xhr.status);
    });

For a production application, display a user-friendly message on the page and log technical details for debugging. Avoid exposing sensitive server errors to visitors.

10. Common Mistakes When Using jQuery with JSON and APIs

Mistake 1: Forgetting to include jQuery

If jQuery is not loaded before your code executes, $ may be undefined.

Solution: Include the jQuery library before your script.

Mistake 2: Treating a JSON string like a JavaScript object

A JSON string and a parsed JavaScript object are different.

Solution: Parse a raw JSON string when necessary. If jQuery already parsed the response, access its properties directly.

Mistake 3: Using the wrong property name

If the API returns title, using data.name will not return the title.

Solution: Check the actual API response and use the correct property names.

Mistake 4: Ignoring errors

A request may fail even when the code looks correct.

Solution: Add .fail() or an error callback and test the failure case.

Mistake 5: Assuming every API allows cross-origin requests

Some APIs do not permit requests from every website.

Solution: Check the API's CORS policy. If required, make the request through your own backend where appropriate.

Mistake 6: Inserting untrusted data as HTML

Using .html() with untrusted API data can create a cross-site scripting risk.

Solution: Prefer .text() for plain text. If HTML must be rendered, sanitize it with an appropriate trusted sanitization library.

11. Best Practices

  • Use $.getJSON() for straightforward JSON GET requests.

  • Use $.ajax() when you need more control over request options.

  • Handle both success and error cases.

  • Validate the response structure before using it.

  • Use .text() to insert untrusted text safely.

  • Do not expose private API keys or secrets in frontend code.

  • Follow the API's authentication and rate-limit requirements.

  • Avoid sending sensitive information through insecure connections.

  • Show a loading indicator when requests may take time.

  • Test your application with successful, empty, and failed responses.

12. Frequently Asked Questions

Q1. Can jQuery work with JSON?

Yes. jQuery supports JSON responses through methods such as $.getJSON() and $.ajax().

Q2. What is $.getJSON() used for?

It sends a GET request and expects a JSON response from the specified URL.

Q3. Is JSON the same as an API?

No. JSON is a data format. An API is an interface that allows software systems to communicate. An API may use JSON to exchange data.

Q4. What is the difference between $.getJSON() and $.ajax()?

$.getJSON() is a convenient method for retrieving JSON using GET. $.ajax() provides more configuration options, including different HTTP methods and request settings.

Q5. Do we need JSON.parse() when using jQuery AJAX?

Not usually when jQuery is already configured to parse a JSON response. You may need JSON.parse() when you receive a raw JSON string outside that automatic parsing process.

Q6. Can jQuery send data to an API?

Yes. You can use $.post() or $.ajax() to submit data to an API, depending on the API's requirements.

Q7. Why is my API request failing?

Possible reasons include an incorrect endpoint, network problems, server errors, authentication requirements, or CORS restrictions. Check the browser's developer tools and the API documentation.

13. jQuery JSON and API Interview Questions

  1. What is JSON, and why is it used in APIs?

  2. What is the purpose of the $.getJSON() method?

  3. What is the difference between JSON.parse() and JSON.stringify()?

  4. What is the difference between contentType and dataType in $.ajax()?

  5. How do you handle an API request failure in jQuery?

  6. How can you loop through an array returned by an API?

  7. What is CORS, and how can it affect an API request?

  8. Why should you avoid inserting untrusted API responses using .html()?

14. Practice Exercises

Try these exercises to improve your understanding:

  1. Create a button that loads one post from a demo API.

  2. Display five posts using $.getJSON() and $.each().

  3. Create a user list that displays each user's name and email.

  4. Use $.ajax() to retrieve JSON data and handle errors.

  5. Send a sample JSON object to a test API using POST.

  6. Display a loading message while the request is in progress.

  7. Show a friendly message when an API returns an empty array.

15. Multiple-Choice Questions (MCQs)

Q1. What does JSON stand for?

A. JavaScript Object Notation

B. Java Source Object Network

C. JavaScript Online Network

D. Joined Standard Object Names

Correct Answer: A. JavaScript Object Notation

Q2. Which jQuery method is designed for retrieving JSON data?

A. $.hideJSON()

B. $.getJSON()

C. $.cssJSON()

D. $.removeJSON()

Correct Answer: B. $.getJSON()

Q3. Which method converts a JavaScript object into a JSON string?

A. JSON.parse()

B. JSON.stringify()

C. JSON.convert()

D. JSON.object()

Correct Answer: B. JSON.stringify()

Q4. Which callback can handle a failed jQuery AJAX request?

A. .fail()

B. .successOnly()

C. .completeError()

D. .loadFailOnly()

Correct Answer: A. .fail()

Q5. Which jQuery method can provide detailed AJAX configuration?

A. $.ajax()

B. $.each()

C. $.text()

D. $.parent()

Correct Answer: A. $.ajax()

Conclusion

Using jQuery with JSON and APIs helps developers build interactive webpages that retrieve and submit data without reloading the entire page.

The key concepts to remember are:

  • APIs provide an interface for communication between applications.

  • JSON is a common format for exchanging structured data.

  • $.getJSON() is useful for retrieving JSON data.

  • $.ajax() provides flexible request configuration.

  • JSON.parse() converts JSON text into a JavaScript value.

  • JSON.stringify() converts a JavaScript value into JSON text.

  • Proper error handling and safe rendering are essential for reliable applications.

Start by loading a simple JSON response, then practise displaying arrays of records and sending data to a test API. These skills will help you build more advanced jQuery projects.

←
Post 12 of 15
→