jQuery Load Complete Guide for Beginners to Experts – Examples & Codes

jQuery Load Complete Guide for Beginners to Experts – Examples & Codes
Now learn all the ways to use the jQuery Load method for doing AJAX calls.

The best part?

I’m going to show you how to fetch contents of external files (HTML, TEXT, XML, JSON) with the .load() method. In the end, I will also read data from database using this method.

The full codes can be downloaded by the link given at the end of this tutorial. Also check the DEMO links for understanding the working of the various codes.

In short: you’ll love this guide.

Let’s get started.

The jQuery Load method is the simplest yet powerful enough to fulfill all your AJAX requirements. It can load data from external files (like HTML, TXT, XML, JSON) asynchronously.

jQuery Load Syntax

It’s syntax is given below:

$(selector).load(url,data,callback);

Parameter’s Description
  • url – The Required Parameter containing the URL to which the AJAX request is made. It could be any file like HTML, TXT, JS, ASP, PHP, CGI, etc.
  • data – The Optional Parameter that can be in the form of an object or string. The parameter’s values are sent with the request in the form of HTTP POST method.
  • callback – The Optional Parameter, a function that is executed when the AJAX request completes. It’s syntax is Function(string response, string status, jqXHR jqXHR ).

The jqXHR object is a superset of the XMLHTTPRequest object. Use it if you receive an error during the jQuery AJAX call, and find out the status and statusText of the error.

Example 1: Using jQuery Load to Fetch Contents of a Text File

Let’s use load() function to get the contents from a text file.

<button id="loadTextFile">Try</button>
<div id="textData"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#loadTextFile").click(function (e) {
            $("#textData").load("file.txt");
        });
    });
</script>

Here in the button click event, I called the load function which initiates the AJAX request to a file with name as file.text. It then shows it’s content in the div element called textData.

DEMO

Capturing jQuery Load Error

If the jQuery Load method gives some error (like when initiating an AJAX request to a non existing file) then I can use it’s 3rd optional parameter (callback function) to find the cause of this error.

<button id="loadNoTextFile">Try</button>
<div id="textNoData"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("#loadNoTextFile").click(function (e) {
        $("#textNoData").load("no-file.txt", function (response, status, xhr) {
            if (status == "error")
                $("#textNoData").html("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
});
<script>

I tried to make .load() call to a non-existing file (nofile.txt) and used the callback function to know what caused this error. Here it will show Error: 404: Not Found message in the div called textNoData.

The callback function is very helpful in debugging the code.

DEMO

With .load() method you can also read contents of an XML file, see tutorial – jQuery Load XML Example.

Example 2: Using jQuery Load to Fetch Contents of a HTML File

Suppose I want to fetch the contents of a HTML file from AJAX. Here I can use the load function to do this job.

See the below code:

<button id="loadHtmlFile">Try</button>
<div id="htmlData"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("#loadHtmlFile").click(function (e) {
        $("#htmlData").load("file.html");
    });    
});
<script>

In the above code the whole HTML of the file.html is fetched and is shown inside the div called htmlData.

DEMO

Fetching a portion of DOM from an HTML File

Sometimes we are interested in fetching only a certain area of the DOM, it can be a table, paragraph, div or any other element. In this case, I can give the id or the class of the element to be fetches, after the file name.

In the below image I have marked a paragraph element that needs to be fetched.

jQuery Load to fetch a DOM portion of an HTML file

This fetching can be easily done, by providing the id of the element after the file name, in the jQuery load function.

The code for this is given below:

$("#htmlData").load("file.html #second");

DEMO

Example 3: Using jQuery Load to Fetch Data From Database

In Database driven websites you can use jQuery Load for fetching data from a Database and then show it inside some html element like a div. This procedure involves 3 parts.

  • Fetching a portion of DOM from an server side page (.php, .aspx, etc) using load function.
  • In the server side page, get the data from the DB.
  • Put this data inside a control like div. This div is fetched by the jQuery load function.

To understand this let us create a small Sports Application in ASP.NET.

Sports Application – a Database powered which uses jQuery Load Function

In this application there are 2 pages – a HTML and a .aspx page.

  • There are 2 dropdown controls in the HTML page – one for the sports person’s name and other for the sports that he plays.
  • After selecting the options from both the dropdowns and clicking the button, I call the jQuery Load method and pass the dropdown values to the .aspx page.
  • The .aspx page queries the DB and gets the sports person’s information. It then updates a div with this information.
  • Finally the load function fetches this div and shows the information to the user.

The below image describes this procedure.

jquery load working

The html page code is shown below:

<div id="message"></div>
<select id="sportSelect">
    <option value="Select">Select Sports</option>
    <option value="Tennis">Tennis</option>
    <option value="Football">Football</option>
    <option value="Cricket">Cricket</option>
</select>
<select id="playerSelect">
    <option value="Select">Select Sports Person</option>
    <option value="Maria Sharapova">Maria Sharapova</option>
    <option value="Cristiano Ronaldo">Cristiano Ronaldo</option>
    <option value="Sachin Tendulkar">Sachin Tendulkar</option>
</select>
<button id="loadDatabase">Try</button>
<div id="dbData"></div>

Now with the jQuery Load method I make AJAX request to the result.aspx page and fetches a div with id called playerData.

I also passed the values of the 2 dropdowns using the optional data parameter.

I have also used the optional callback function to show alert in case of any error.

The div with id dbData will show the player’s information.

This jQuery code is given below:

$("#dbData").load("result.aspx #playerData", { "sport": "" + $("#sportSelect").val() + "", "player": "" + $("#playerSelect").val() + "" }, function (response, status, xhr) {
    if (status == "error")
        alert("Error: " + xhr.status + ": " + xhr.statusText);
});

Now let’s move towards the code of results.aspx page. It has only a div with id playerData where the player information will be set.

<div id="playerData" runat="server">
</div>

In the .cs page get the dropdown values using Request.Form like this:

string sport = Request.Form["sport"];
string player = Request.Form["player"];

Once I have the dropdown values, I can simply do a basic query to my DB and get the player’s information.

The .cs page code is given below:

List<MyDataBase> myDataBase;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadData();
        SearchDatabase();
    }
}

void SearchDatabase()
{
    string sport = Request.Form["sport"];
    string player = Request.Form["player"];

    try
    {
        string information = myDataBase.FirstOrDefault(x => x.sport == sport & x.player == player).information;
        playerData.InnerHtml = information;
    }
    catch (Exception ex) {
        playerData.InnerHtml = "NO DATA";
    }
}

void LoadData()
{
    myDataBase = new List<MyDataBase>();
    myDataBase.Add(new MyDataBase() { sport = "Tennis", player = "Maria Sharapova", information = "Maria Sharapova is a Russian professional tennis player. A United States resident since 1994,[4] Sharapova has competed on the WTA tour since 2001. She has been ranked world No. 1 in singles by the WTA on five separate occasions, for a total of 21 weeks. She is one of ten women, and the only Russian, to hold the career Grand Slam. She is also an Olympic medalist, having earned silver for Russia in women's singles at the 2012 Summer Olympics in London." });
    myDataBase.Add(new MyDataBase() { sport = "Football", player = "Cristiano Ronaldo", information = "Cristiano Ronaldo is a Portuguese professional footballer who plays for Spanish club Real Madrid and the Portugal national team. He is a forward and serves as captain for Portugal. In 2008, he won his first Ballon d'Or and FIFA World Player of the Year awards. Ronaldo then won the FIFA Ballon d'Or in 2013 and 2014. He received his fourth Ballon d'Or in 2016, the most for a European player in the history of the award. One year earlier, Ronaldo had scored his 500th senior career goal for club and country." });
    myDataBase.Add(new MyDataBase() { sport = "Cricket", player = "Sachin Tendulkar", information = "Sachin Tendulkar is a former Indian cricketer and captain, widely regarded as one of the greatest batsmen of all time.[4] He took up cricket at the age of eleven, made his Test debut on 15 November 1989 against Pakistan in Karachi at the age of sixteen, and went on to represent Mumbai domestically and India internationally for close to twenty-four years. He is the only player to have scored one hundred international centuries, the first batsman to score a double century in a One Day International, the holder of the record for the number of runs in both ODI and Test cricket, and the only player to complete more than 30,000 runs in international cricket." });
}

class MyDataBase
{
    public string sport { get; set; }
    public string player { get; set; }
    public string information { get; set; }
}

Explanation

You will note that in the above code I am using a list object instead of DB. I am performing a LINQ Query to fetch the respective player’s information. At the last, putting this information inside the playerData element.

Try the code of this Sports Application and download it from the links below:

DEMO DOWNLOAD

The most important thing to note here is that the .load() function fetches the ‘playerData’ element’s value and show it in the HTML page. You should also check this related tutorial – Bind GridView with Paging using jQuery Load with No Page Refresh.
Conclusion

Do not underestimate the power of jQuery’s .load() method which can do any sort of AJAX work in your website. I have covered 20 to 30 tutorial on AJAX usage which will satisfy all your need.

The 4 important AJAX topics of jQuery which you can’t miss are:

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.