- jQuery — AJAX load() Method
- jQuery and AJAX is FUN.
- Example
- Example
- Example
- jQuery AJAX Reference
- .load()
- .load( url [, data ] [, complete ] ) Returns: jQuery
- version added: 1.0 .load( url [, data ] [, complete ] )
- Callback Function
- Request Method
- Loading Page Fragments
- Script Execution
- Additional Notes:
- Examples:
- load event
- .on( "load" [, eventData ], handler ) Returns: jQuery
- version added: 1.7 .on( "load" [, eventData ], handler )
- Examples:
- .trigger( "load" ) Returns: jQuery
- version added: 1.0 .trigger( "load" )
- Books
jQuery — AJAX load() Method
The jQuery load() method is a simple, but powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element.
The required URL parameter specifies the URL you wish to load.
The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
The optional callback parameter is the name of a function to be executed after the load() method is completed.
Here is the content of our example file: «demo_test.txt»:
jQuery and AJAX is FUN.
The following example loads the content of the file «demo_test.txt» into a specific element:
Example
It is also possible to add a jQuery selector to the URL parameter.
The following example loads the content of the element with inside the file «demo_test.txt», into a specific element:
Example
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
- responseTxt — contains the resulting content if the call succeeds
- statusTxt — contains the status of the call
- xhr — contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load() method has succeeded, it displays «External content loaded successfully!», and if it fails it displays an error message:
Example
$(«button»).click(function() <
$(«#div1»).load(«demo_test.txt», function(responseTxt, statusTxt, xhr) <
if(statusTxt == «success»)
alert(«External content loaded successfully!»);
if(statusTxt == «error»)
alert(«Error: » + xhr.status + «: » + xhr.statusText);
>);
>);
jQuery AJAX Reference
For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.
.load()
.load( url [, data ] [, complete ] ) Returns: jQuery
Description: Load data from the server and place the returned HTML into the matched elements.
version added: 1.0 .load( url [, data ] [, complete ] )
Note: Prior to jQuery 3.0, the event handling suite also had a method named .load() . Older versions of jQuery determined which method to fire based on the set of arguments passed to it.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is «success» or «notmodified»), .load() sets the HTML contents of the matched elements to the returned data. This means that most uses of the method can be quite simple:
If no element is matched by the selector — in this case, if the document does not contain an element with — the Ajax request will not be sent.
Callback Function
If a «complete» callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
$( "#result" ).load( "ajax/test.html", function( )
alert( "Load was performed." );
>);
In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Loading Page Fragments
The .load() method, unlike $.get() , allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html , but then jQuery parses the returned document to find the element with an ID of container . This element, along with its contents, is inserted into the element with an ID of result , and the rest of the retrieved document is discarded.
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
Script Execution
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will successfully execute.
However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:
$( "#b" ).load( "article.html #target" );
Additional Notes:
- Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Examples:
Load another page's list items into an ordered list.
load event
.on( "load" [, eventData ], handler ) Returns: jQuery
Description: Bind an event handler to the "load" event.
version added: 1.7 .on( "load" [, eventData ], handler )
This page describes the load event. For the .load() method removed in jQuery 3.0, see .load() .
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
For example, consider a page with a simple image:
img src="book.png" alt="Book" id="book">
The event handler can be bound to the image:
$( "#book" ).on( "load", function( )
// Handler for `load` called.
> );
As soon as the image has been loaded, the handler is called.
In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.
Caveats of the load event when used with images
A common challenge developers attempt to solve using the load shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
- It doesn't work consistently nor reliably cross-browser
- It doesn't fire correctly in WebKit if the image src is set to the same src as before
- It doesn't correctly bubble up the DOM tree
- Can cease to fire for images that already live in the browser's cache
Note: The .live() and .delegate() methods cannot be used to detect the load event of an iframe. The load event does not correctly bubble up the parent document and the event.target isn't set by Firefox, IE9 or Chrome, which is required to do event delegation.
Examples:
Run a function when the page is fully loaded including graphics.
$( window ).on( "load", function( )
// Run code
> );
Add the class bigImg to all images with height greater than 100 upon each image load.
$( "img.userIcon" ).on( "load", function( )
if ( $( this ).height() > 100)
$( this ).addClass( "bigImg" );
>
> );
.trigger( "load" ) Returns: jQuery
Description: Trigger the "load" event on an element.
version added: 1.0 .trigger( "load" )
- Ajax
- Global Ajax Event Handlers
- Helper Functions
- Low-Level Interface
- Shorthand Methods
- Deprecated 1.3
- Deprecated 1.7
- Deprecated 1.8
- Deprecated 1.9
- Deprecated 1.10
- Deprecated 3.0
- Deprecated 3.2
- Deprecated 3.3
- Deprecated 3.4
- Deprecated 3.5
- Basics
- Custom
- Fading
- Sliding
- Browser Events
- Document Loading
- Event Handler Attachment
- Event Object
- Form Events
- Keyboard Events
- Mouse Events
- Class Attribute
- Copying
- DOM Insertion, Around
- DOM Insertion, Inside
- DOM Insertion, Outside
- DOM Removal
- DOM Replacement
- General Attributes
- Style Properties
- Collection Manipulation
- Data Storage
- DOM Element Methods
- Setup Methods
- Properties of jQuery Object Instances
- Properties of the Global jQuery Object
- Attribute
- Basic
- Basic Filter
- Child Filter
- Content Filter
- Form
- Hierarchy
- jQuery Extensions
- Visibility Filter
- Filtering
- Miscellaneous Traversing
- Tree Traversal
- Version 1.0
- Version 1.0.4
- Version 1.1
- Version 1.1.2
- Version 1.1.3
- Version 1.1.4
- Version 1.2
- Version 1.2.3
- Version 1.2.6
- Version 1.3
- Version 1.4
- Version 1.4.1
- Version 1.4.2
- Version 1.4.3
- Version 1.4.4
- Version 1.5
- Version 1.5.1
- Version 1.6
- Version 1.7
- Version 1.8
- Version 1.9
- Version 1.11 & 2.1
- Version 1.12 & 2.2
- Version 3.0
- Version 3.1
- Version 3.2
- Version 3.3
- Version 3.4
- Version 3.5
- Version 3.6
- Version 3.7
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath