LanguagesJavaScriptjQuery Load, GET, and Post methods (AJAX)

jQuery Load, GET, and Post methods (AJAX)

The acronym AJAX stands for Asynchronous JavaScript and XML and is used to display data on the web page and load this data in the background (on the server), without having to reload the entire page. jQuery is a JavaScript library that has been designed to handle events, animations, AJAX requests, and manipulate the DOM tree. JQuery also offers the ability to develop plugins, advanced effects, and widgets, creating dynamic web pages and powerful applications. Therefore, we could say jQuery offers methods for AJAX functionality, and HTML, XML, text, or JSON can be requested from a server using HTTP Get and HTTP Post methods. In the following AJAX web development tutorial, we will detail, with examples, jQuery AJAX methods.

Read: Intro to Web Sockets

jQuery load() Method Examples

The jQuery load() method loads data from a server and then returns the data within the selected item in the DOM tree. The syntax for jQuery load() is: $ (selector).load (URL, date, callback). The URL parameter refers to the URL you want to upload. The optional date parameter indicates the set of query string key/value pairs that is sent in the request made, and the optional callback parameter represents the name of the function that will be executed after the load() method has been completed. Here is an example of how to use the jQuery load() method:

<!DOCTYPE html>
<html>
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     <script>
         $(document).ready(function () {
                $("button").click(function () {
                 $("#div1").load("demo.txt", function (responseTxt, statusTxt, xhr) {
                     if (statusTxt == "success") alert("The content was successfully loaded!");
                     if (statusTxt == "error") alert("Error: " + xhr.status + ": " + xhr.statusText);
                 });
             });
         });
     </script>
</head>
<body>
     <div id="div1"><h2>Changing the initial text</h2></div>
     <button>Click me!</button>
</body>
</html>

In the example above, we displayed a pop-up after finishing the load() method. If the method passed successfully, the message External content loaded successfully! appears in a pop-up.

jQuery load()

jQuery get() Method Example

The jQuery get() method is used to request data from a server via an HTTP Get request. The syntax for jQuery Get is: $.get(URL, callback); The URL parameter refers to the URL you want to request and the callback parameter refers to the name of the function you are performing if the request is successful. In the following example, we will use the get() method to access the data in a file that is on the server:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("demo.asp", function(data, status){
      alert("Data: " + data + "nStatus: " + status);
});
  });
});
</script>
</head>
<body>
<button>Send a request and get the result</button>
</body>
</html>

jQuey get

In the following example, we will take JSON data using the getJson() method. As in the example above, we will use the same parameters: a URL where we will receive the JSON data, the date to be transmitted with the Get request and the last parameter is the callback function that will be called if the request is successful. The date parameter will be JSON because we use the getJson() method, the method that converts the response received from the server into a JSON object. Therefore:

<!DOCTYPE html>
<html>
<head>
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
     <script type="text/javascript">
         $(document).ready(function () {
                $("#clickMeButton").click(function () {
                    $.getJSON("/jquery/getjsondata", { name: "CRISTIAN" }, function (data, textStatus, jqXHR) {
                        $("p").append(data.firstName);
                 });
             });
         });
     </script>
     <style>
         body * {
             padding: 10px;
             margin-left: 10px;
         }
     </style>
</head>
<body>
     <h3>Another jQuery get() method</h3>
     <input type="button" id="clickMeButton" value="Click me!" />
     <div>
         <p></p>
     </div>
</body>
</html>

jQuery getJson Example

Read: An Introdction to REST

jQuery post() Method

Using the post() method, we can request data from the server using the HTTP Post request. The syntax for jQuery post() is: $.post(URL, date, callback). The URL parameter refers to the URL you want to request, the date parameter refers to the date we send with the request, and the callback parameter refers to the name of the function you give it and which will be called if the request was successful. In the following example, we will send some data together with the request via the post() method:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("button").click(function () {
                 $.post(
                     "demo.asp",
                     {
                         name: "Cristian Ionescu",
                         city: "Bucharest",
                     },
                     function (data, status) {
                         alert("Data: " + data + "nStatus: " + status);
                     }
                 );
                });
            });
        </script>
    </head>
    <body>
        <button>Click me!</button>
    </body>
</html>

Consider the following example, in which we send data and receive a response using the post() method:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#clickMeButton").click(function () {
                    $.post("/jquery/submitData", { myData: "post() method is a very useful method!" }, function (data, status, jqXHR) {
                        $("p").append("status: " + status + ", data: " + data);
                 });
                });
            });
        </script>
        <style>
            body * {
                padding: 10px;
                margin-left: 10 px;
            }
        </style>
    </head>
    <body>
        <h3>Another jQuery post() method</h3>
        <input type="button" id="clickMeButton" value="Click me!" />
        <div>
            <p></p>
        </div>
    </body>
</html>
jQuery POST

As in the first example where we used the post() method, here we also used three parameters, namely: URL – the address where we want to send the HTTP Post request and send the desired data, the second parameter represents a date that is in JSON format, where the key is the name of a parameter, and the value indicating the value of the parameter. The third parameter is the callback function, a function that also has some parameters, namely: data, status, and jqXHR(jQuery XMLHttpRequest).

The jqXHR Object is returned by jQuery’s AJAX functions, containing information related to status, statusText, responseText, responseXML, getAllResponseHeaders() function, getResponseHeader() function, and board(). This information will be available when the server sends a response back, it is inside the callback functions.

Summary of jQuery AJAX Methods

Using these methods mentioned above is very useful, because through the load() method, developers can upload data from a server, returning the data to the item you selected in the DOM tree, the get() method is very useful when the URL for future use, and the post() method is useful in securely processing your sensitive data. These methods are most commonly used for communication between clients and servers.

Read more JavaScript programming and web development tutorials.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories