What is the difference between jQuery.load() and jQuery.ajax() methods in jQuery?


jQuery ajax() method

The jQuery.ajax( options ) method loads a remote page using an HTTP request. $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.

Here is the description of all the parameters used by this method −

  • options − A set of key/value pairs that configure the Ajax request. All options are optional.

Assuming we have the following HTML content in result.html file −

<h1>THIS IS RESULT...</h1>

Example

The following is an example showing the usage of this method. Here, we make use of success handler to populate returned HTML −

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("#driver").click(function(event){
               $.ajax( {
                  url:'result.html',
                  success:function(data) {
                     $('#stage').html(data);
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:blue;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

jQuery load() method

The load( url, data, callback ) method loads data from the server and places the returned HTML into the matched element.

Here is the description of all the parameters used by this method −

  • url − A string containing the URL to which the request is sent.
  • data − This optional parameter represents a map of data that is sent with the request.
  • callback − This optional parameter represents a function that is executed if the request succeeds.

Assuming we have following HTML content in result.html file −

<h1>THIS IS RESULT...</h1>

Example

The following is the code snippet showing the usage of this method.

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("#driver").click(function(event){
               $('#stage').load('result.html');
            });
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

Updated on: 17-Feb-2020

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements