jQuery Ajax - load() method

AJAX stands for Asynchronous JavaScript And XML, it is a technique for creating fast and dynamic web pages.
Ajax lets us send requests from the browser to the server, and manage the server response without page reload, so we can update a part of the page while the user remains on the same page.
jQuery has multiple methods (functions) for AJAX. In this tutorial it's presented the load() method.

load() method

The load() method is a simple AJAX function that loads data from the server and place the returned HTML into the matched element on the current web page.
Syntax:
$('element').load(url, data, complete)
- url - specifies the URL to which the request is sent.
- data - (optional) a string that is sent to the server with the request.
- complete - (optional) a function that is executed when the request completes. It has three additional parameters (response, status, xhr).
          • response - contains the result data from the request.
          • status - contains the status of the request, one of the strings "success", "notmodified", "error", "timeout", or "parsererror".
          • xhr - contains the XMLHttpRequest object.

For security reasons, the external file with the content you load must be stored on the same domain (server) as the web page from which your script is running.


Let's see a simple example. First we create a HTML content into an external file on the server, named extern.html.

The extern.html file

<h2>Content in extern.html</h2>
<div id="cnt">Example jQuery Ajax, the load() method.
<p>Some text content in extern.html</p></div>

Then we create a simple web page (named test.html), with a link and a <div> where we place the content loaded from "extern.html", when the link is clicked.

The test.html file

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax Test</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // select all the links with class="lnk", when one of them is clicked, get its "href" value
  // load the content from that URL and place it into the tag with id="content"
  $('a.lnk').click(function() {
    var url = $(this).attr('href');
    $('#content').load(url);
    return false;
  });
});
--></script>
</head>
<body>
<h1>Web page test.html</h1>
<a href="extern.html" title="Get extern" class="lnk">Get extern</a>
<div id="content">Initial content in test.html</div>
</body>
</html>
We select all the links with class="lnk", when one of them is clicked, gets its "href" value (with .attr('href') ) and pass it into the load() function, which will load the content from that URL and place it into the tag with id="content".
The return false; statement is used to prevent the browser to open that page when the link is clicked.
This example will display the following result (click on the link below):
Web page test.html
Get extern
Initial content in test.html

As you can notice, the load(url) method include the entry contents from "extern.html" into <div id="content">, without reloading or opening another page.
If the comunication with the server is slow or the content is to big, the loading action can take some more time, during this time the user doesn't know what hapsens. So, it is good to add a "loading..." notification.
Also, we can add on the page only a portion of the loaded content, by specifying the selectors as part of the URL string.
The format for adding a "loading..." notification and using selectors with load is very simple:
$('element').html('loading...').load('url selector')
- The "url" and the "selector" must be separated by space, in the same string.

Let's see an example. We load the same content from "extern.html", but we include on the page only the paragraph which is in the <div> with id="cnt".
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax Test</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // select all the links with class="lnk", when one of them is clicked, get its "href" value
  // adds a "loading..." notification, load the content from that URL and
  // place only the paragraph which is in the #cnt into the tag with id="content"
  $('a.lnk').click(function() {
    var url = $(this).attr('href');
    $('#content').html('<h4>Loading...</h4>').load(url+ ' #cnt p');
    return false;
  });
});
--></script>
</head>
<body>
<h1>Web page test.html</h1>
<a href="extern.html" title="Get extern" class="lnk">Get extern</a>
<div id="content">Initial content in test.html</div>
</body>
</html>
To see the result, click on the link below:
Web page test.html
Get extern
Initial content in test.html

If the loading process is fast you don't see the "loading..." notification. This is useful when the load() method accesses a server script (like a PHP) file that processes the informations and then return a HTML content, which can take some more time.
- The URL can also have a form like:   file.php?id=value

Loading content from a PHP file via Ajax

You can use jQuery load() method to load HTML content from a script file (like PHP, or ASP), and to send some data to be processed by the server script.
In this case we add a second parameter (data) in the load() method:
$('element').load('script.php', data)
- data can contain a string with "key=value" pairs separated by "&" that will be send through GET method. Or can contain an object (JSON type). If data is provided as an object, will be send through POST method.

Let's see an example. This time we'll load the content from an external PHP file, named "script.php", which contains the following code:

The script.php file

<?php
// check if there is data sent through GET, with key "pag"
if(isset($_GET['pag'])) {
  $pag = strip_tags($_GET['pag']);       // gets data and removes posible tags

  // sets a HTML content according to the value of $pag
  if($pag=='php') {
    $rehtml = '<b>PHP-MySQL course and tutorials:</b> <u>http://coursesweb.net/php-mysql/</u>';
  }
  else if($pag=='ajax') {
    $rehtml = '<b>AJAX course:</b> <u>http://coursesweb.net/ajax/</u>';
  }
  else {
    $rehtml = '<b>Free Web Development courses:</b> <u>http://coursesweb.net</u>';
  }

  echo $rehtml;        // output (return) the value of $rehtml
}
else {
  // if no $_GET with key "pag", returns a error message
  echo 'Error: Invalid data';
}
?>
- The necessary explanations about this script are in its code.

Now we create the web page that accesses the "script.php" file via Ajax.
It contains a form with a select (which has three options), a Submit button and a <div> where we place the content loaded from "script.php", when the user submit the form.
The data that will be sent to the PHP script is defined with the value selected in the Select list. For other details, see the comments in code.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - PHP</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // when the user submit a form
  $('form').submit(function() {
    var url = $(this).attr('action');       // gets the url from "action" attribute of the current form

    // define data to be send to PHP
    // with the key "pag" and the value selected in the select list (with id="pag")
    var data = 'pag='+ $('#pag').val();

    // adds a "loading..." notification, load the content from url (passing the data)
    // and place it into the tag with id="content"
    $('#content').html('<h4>Loading...</h4>').load(url, data);
    return false;
  });
});
--></script>
</head>
<body>
<div id="content">Initial content ...</div>
<form action="script.php" method="get">
 Select course:
 <select name="pag" id="pag">
  <option value="other">Other</option>
  <option value="php">PHP</option>
  <option value="ajax">Ajax</option>
 </select>
 <input type="submit" id="submit" value="Submit" />
</form>
</body>
</html>

Select an option from the list and click the "Submit" button:
Initial content ...
Select course:

If you want to send multiple values to the PHP script, add them in a string with "key=value" pairs separated by "&":
var data = 'id=val1&name=val2&pag=val3';
If you want to send an array of values, or an object, use the JSON syntax (data will be sent through POST):
var data = { 'array[]': ["value1", "value2", "value3"] };

Check the Ajax request status and errors

The load() method has a third parameter wich is a function with three parameters:
$('element').load(url, data, function(response, status, xhr){
  // code to execude when the Ajax request is sent
})
  - response - contains the result data from the request.
  - status - contains the status of the request, one of the strings "success", "notmodified", "error", "timeout", or "parsererror".
  - xhr - contains the XMLHttpRequest object. To get the status contained in this object, use xhr.status , and xhr.statusText

Using the "status" parameter we can check if the request was sucesfully sent or occured an error, and perform different instructions according to the status.

Let's see how we work with the status parameter.
In the following example we have two links, one to the "script.php" file (created in the example above), and the other to a nonexistent file.
If the value of the status parameter is "success", gets the response, else, if is "error", we set an error mesage.
The response from the server, or the error is inserted into a <div> with id="content".
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - check status</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // select all the links with class="lnk", when one of them is clicked, get its "href" value
  // load the content from that URL and check the "status" of the request
  // place the response or an error message into the tag with id="content"
  $('a.lnk').click(function() {
    var url = $(this).attr('href');
    $('#content').load(url, function(response, status, xhr) {
      // check the status, if "success", place the response into #content
      // else, if "error", define an error message and insert it into #content
      // else, display an Alert with the status
      if(status=='success') {
        $('#content').html(response);
      }
      else if(status=='error') {
        var ermsg = '<i>There was an error: '+ xhr.status+ ' '+ xhr.statusText+ '</i>';
        $('#content').html(ermsg);
      }
      else { alert(status); }
    });
    return false;
  })
});
--></script>
</head>
<body>
<h2>jQuery Ajax example</h2>
<div id="content">Initial content...</div>
<a href="script.php?pag=ajax" title="link to script.php" class="lnk">Link to script.php</a>
<a href="nofile.php" title="link to nofile.php" class="lnk">Link to nofile.php</a>
</body>
</html>
- The else { alert(status); } statement was added for the case when the status of the request is other then "success" or "error".
Click on the two links above to see the result:
jQuery Ajax example
Initial content...
Link to script.php   Link to nofile.php