Cover Image for jQuery get() method
78 views

jQuery get() method

The jQuery get() method is used to send an HTTP GET request to the server and retrieve data. It is one of the shorthand AJAX methods provided by jQuery for making AJAX requests. The get() method is typically used to fetch data from a server and receive a response in various formats such as JSON, XML, HTML, or plain text.

Here’s the basic syntax of the get() method:

$.get(url, data, success, dataType);

Parameters:

  • url: The URL to which the request is sent.
  • data: (Optional) Data to be sent to the server with the request.
  • success: (Optional) A callback function to be executed if the request succeeds.
  • dataType: (Optional) The type of data expected to be returned from the server. It can be “json”, “xml”, “html”, “text”, etc.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery get() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="load-data">Load Data</button>
    <div id="output"></div>

    <script>
        $(document).ready(function() {
            $('#load-data').click(function() {
                // Send a GET request to retrieve data from a JSON file
                $.get('data.json', function(data) {
                    // Display the data in the output div
                    $('#output').text(JSON.stringify(data));
                }, 'json');
            });
        });
    </script>
</body>
</html>

In this example, we have a button with the ID “load-data” and a div with the ID “output.” When the button is clicked, we use the get() method to make a GET request to the “data.json” file, which contains JSON data. Upon successful retrieval, the JSON data is displayed in the “output” div.

The get() method is a convenient way to perform AJAX requests and retrieve data from the server without having to write a lot of boilerplate code. It is widely used for fetching data from APIs, loading content dynamically, and more.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS