jQuery -

GetJSON


Introduction to jQuery GetJSON

The $.getJSON() method in jQuery is used to load JSON-encoded data from the server using a GET HTTP request. This method simplifies the process of fetching JSON data and is commonly used in AJAX-driven applications. This tutorial covers the basics and advanced uses of the $.getJSON() method with detailed examples and useful tips.


1. Basic Usage of $.getJSON()

The $.getJSON() method is used to perform an HTTP GET request and load JSON data from the server.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Basic GetJSON Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://jsonplaceholder.typicode.com/posts/1", function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch JSON Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to use the $.getJSON() method to fetch JSON data from a server.


2. Basic Usage with $.ajax()

The $.ajax() method with method: 'GET' can also be used to fetch JSON data. This method provides more flexibility and control over the request.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Basic AJAX JSON Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch JSON Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use the $.ajax() method to fetch JSON data from a server.


3. Sending Data with $.getJSON()

You can send data to the server with the $.getJSON() method by passing data as an object.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>GetJSON with Data Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://jsonplaceholder.typicode.com/posts", { userId: 1 }, function(data){
                    let items = data.map(item => `<li>${item.title}</li>`).join("");
                    $("#result").html(items);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Params</button>
    <ul id="result"></ul>
</body>
</html>
        
    

This example demonstrates how to send data to the server using the $.getJSON() method.


4. Sending Data with $.ajax()

You can send data to the server with the $.ajax() method by passing data as an object and setting the method to 'GET'.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX with Data Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts",
                    method: "GET",
                    data: { userId: 1 },
                    dataType: "json",
                    success: function(data){
                        let items = data.map(item => `<li>${item.title}</li>`).join("");
                        $("#result").html(items);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Params</button>
    <ul id="result"></ul>
</body>
</html>
        
    

This example shows how to send data to the server using the $.ajax() method.


5. Handling JSON Data

Handling JSON data returned from the server involves parsing the JSON and updating the DOM elements with the data.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>JSON Data Handling Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://jsonplaceholder.typicode.com/posts/1", function(data){
                    $("#result").html(`<p>ID: ${data.id}</p><p>Title: ${data.title}</p><p>Body: ${data.body}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch JSON Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to handle JSON data returned from a server.


6. Combining GetJSON with DOM Manipulation

Combining the $.getJSON() method with DOM manipulation allows you to dynamically update parts of your web page with data from the server.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>GetJSON DOM Manipulation Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data){
                    let items = data.slice(0, 5).map(item => `<li>${item.title}</li>`).join("");
                    $("#list").html(items);
                }).fail(function(){
                    $("#list").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch and Display List</button>
    <ul id="list"></ul>
</body>
</html>
        
    

This example shows how to update a list dynamically with data fetched via $.getJSON().


7. Using Callbacks with $.getJSON()

The $.getJSON() method accepts callback functions for success and error events.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>GetJSON Callbacks Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://jsonplaceholder.typicode.com/posts/1", function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                }).always(function(){
                    console.log("Request completed");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Callbacks</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to use callbacks with the $.getJSON() method.


8. Using Callbacks with $.ajax()

The $.ajax() method accepts callback functions for success, error, and complete events.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Callbacks Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    },
                    complete: function(){
                        console.log("Request completed");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Callbacks</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use callbacks with the $.ajax() method.



9. Error Handling in $.getJSON()

Proper error handling in AJAX requests is crucial for a good user experience. The $.getJSON() method provides an error callback to handle issues.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>GetJSON Error Handling Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.getJSON("https://invalid-url.com/posts/1", function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                }).fail(function(xhr, status, error){
                    $("#result").html(`<p>Error: ${status}</p>`);
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to handle errors in a $.getJSON() request.


10. Error Handling in $.ajax()

Proper error handling in AJAX requests is crucial for a good user experience. The $.ajax() method provides an error callback to handle issues.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Error Handling Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://invalid-url.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(xhr, status, error){
                        $("#result").html(`<p>Error: ${status}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to handle errors in a $.ajax() request.


11. Caching in $.getJSON()

You can control caching in AJAX requests to improve performance. The $.getJSON() method allows you to disable caching.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>GetJSON Caching Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    cache: false,
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Caching</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to disable caching in a $.getJSON() request.


12. Caching in $.ajax()

You can control caching in AJAX requests to improve performance. The $.ajax() method allows you to disable caching.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Caching Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    cache: false,
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Caching</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to disable caching in a $.ajax() request.


13. Advanced Usage of $.ajax()

The $.ajax() method can be combined with other jQuery methods for advanced functionality.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Advanced AJAX JSON Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",
                    beforeSend: function(){
                        console.log("Request is about to be made");
                    },
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    },
                    complete: function(){
                        console.log("Request completed");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data with Advanced Options</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates advanced usage of the $.ajax() method.