jQuery AJAX load method

The method loadloads the HTML code received from the server into an element on the page. It accepts the following parameters:

  • url: required parameter containing the address of the resource that the request will access
  • data: optional parameter containing a simple javascript object or string to be sent to the server along with the request
  • complete(responseText, textStatus, XMLHttpRequest): optional – a callback function that will be executed when the request completes.

In the previous paragraph, the simplest example of using the method was shown load:

      <button>Download</button>
        <div id="news"><h3>No news</h3></div>
        <script type="text/javascript">
        $(function(){
            $('button').click(function(){
                $('#news').load('ajax.php');
            });
        });
        </script>
        

Using Data in a Request

If the second parameter – data – is not defined, then the request is executed as a GET request. If we use the data parameter, then a POST request is made, and the data is transmitted as when submitting the form. And by applying the appropriate methods on the server side, we can get the transferred data. Let’s change the previous example:

      <button>Download</button>
        <div id="news"><h3>No news</h3></div>
        <script type="text/javascript">
        $(function(){
            $('button').click(function(){
                $('#news').load('ajax.php', {'event':'Start of USA Championship', 'date':'13.07.2022'});
            });
        });
        </script>

Here, as the second parameter, we are passing a javascript object that defines two properties: event and date. Now we will receive this data on the server and return it in response to the client:

<?php
    $event=$_POST['event'];
    $date=$_POST['date'];
    echo "<h3>" . $event . "</h3><h5>" . $date . "</h5>";
?>

Now, by clicking on the button, the data passed in the second parameter will be returned back to the client:

Using the callback function

By using the third parameter, the complete callback function, we can perform some additional related actions when the request completes. Well, the simplest example:
displaying a request status notification:

$('#news').load('ajax.php', function(){alert('Request completed');});