Click here to Skip to main content
12,761,826 members (43,500 online)
Click here to Skip to main content
Add your own
alternative version

Stats

8.3K views
40 downloads
25 bookmarked
Posted 25 Jan 2017

4 Ways To Use jQuery Load in Your Website

, 7 Feb 2017 CPOL
Rate this:
Please Sign up or sign in to vote.
This article explains how useful the jQuery Load method is for doing AJAX calls in our web projects. I will explain the 4 ways/situtations where you can use this method and create a get feature for the users.

Introduction

The jQuery Load is the simplest and all-purpose function that can be used for making all types of AJAX calls. In web projects, there are times when you need to apply AJAX calls, to either fetch data from a database or through other files (text, html, xml, json, etc.). Here, jQuery Load method proves to be very handy.

Let us discuss some ways where you can use this method in your web projects.

1. Read Text File Data of A Small Factory

Text File content with jQuery Load

Text files are the simplest ways to store information. For example, in small factories, every labour’s information is stored in separate text files. All these text files are uploaded on the web server so that the company’s administrators can access them over the internet.

A web developer's work here, would be to show the labours information in a web page. For this, the developer can simply create a web page, add few divs which will show this information. Then, make an jquery ajax call to these text files using jquery load method. Finally, showing the information inside these divs.

For beginners who are new to jQuery Load, I would like you to check the syntax, parameters and return type of this function at jQuery Load.

The Code

<script>
    $(document).ready(function () {
        $("#labour").load("Michael-James.txt", function (response, status, xhr) {
            if (status == "error")
                $("#textData").html
        });
    });
</script>

Explanation – In the above web page, we are showing a labour’s (named “Michael James”) information inside a div (with id “labour”). We are calling the jQuery Load method to read the “Michael-James.txt” file. This text file contains the information about the labour.

The jQuery Load method searches this text file in the same folder where the web page is kept.

If the text files are kept in some other location, then give its relative path to the jQuery Load method.

Example – If the text file is kept inside a folder “labourFolder” (which is kept in the root), the jQuery Load syntax will look like:

$("#labour").load("/labourFolder/Michael-James.txt", 
function (response, status, xhr) {
    if (status == "error")
        $("#textData").html
 });

2. Get Product Information and Prices from JSON

JSON File content with jQuery Load

In the ecommerce world, distributed applications communicate with each other to get updated product prices and information. For example - a big distributer stores the current prices of the products in a JSON file.

This file is very small in size and is sent to the small shop keeper & partners to their email address. Through this JSON file, they can know about the current prices of the distributer’s products.

The job of a web developer, working for the shop keeper, can use the jQuery Load method to fetch this JSON and show the contents inside a web page. This makes it easy for the shop keepers to find out the current prices of the products. (Note that the JSON format is not understandable for a common man).

The Code

<button id="productButton">Try</button>
<div id="productJsonDiv"></div>
<div id="productHtmlDiv"></div>
$("#productJsonDiv").load
("product.json", function (response, status, xhr) {
    $(".displayPara").css("display", "block");
    var json = JSON.parse($("#productJsonDiv").html());
    var table = $("<table><tr><th>Product</th>
    <th>Color</th><th>Price</th></tr>");
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $("<tr>");
        tr.append("<td>" + json[i].Product + "</td>");
        tr.append("<td>" + json[i].color + "</td>");
        tr.append("<td>" + json[i].Price + "</td>");
        tr.append("</tr>");
        table.append(tr);
    }
    table.append("</table>");
    $("#productHtmlDiv").html(table);
    if (status == "error")
        $("#textNoData").html
        ("Error: " + xhr.status + ": " + xhr.statusText);
});

Explanation – On the button “productButton” click event, the jQuery Load fetches the product JSON file. Once the JSON is fetched, it is parsed to HTML and shown in the table form, on the web page.

The products' information in the table form is very easy to understand for the common man.

Note – In place of JSON, sometimes XML is also used. The above jQuery Load code will work for the XML file too, with few modifications.

3. Read Secure Information from the Database

Secured Information Fetch From Database Using  jQuery Load

There should be proper security applied to the websites and jQuery Load works very well in this regard. For example, using jQuery Load, you can authenticate users and provide secured information only to the authenticated users.

Consider a situation – you have a web page where there are two input controls, one for entering username and the other for entering password. Now a user has to enter his username and password them. The system checks his username and password, and only if they are correct, then his secured information is shown to him.

This prevents unauthenticated users from accessing secret information from the database.

This is how we can make the code for this situation.

The Code

<input id="usernameInput" 
type="text" placeholder="username" />
<input id="passwordInput" 
type="text" placeholder="password" />
<button id="databaseButton">Try</button>
<div id="databaseDiv"></div>

$("#databaseButton").click(function (e) {
    $("#databaseDiv").load("result.aspx #dbInformation", 
    { "username": "" + 
$("#usernameInput").val() + "", 
"password": "" + 
    $("#passwordInput").val() + "" }, 
function (response, status, xhr) {
        if (status == "error")
            $("#databaseDiv").html("Error: " + 
            xhr.status + ": " + xhr.statusText);
    });
});

Explanation – We are passing the input values to a server side page “result.aspx” and we are loading this server side page’s “#dbInformation” through the jQuery Load method (“dbInformation” is a div in the server page).

All this is done from just a single line code.

Now in the server side page “result.aspx”, we are checking the username and password to authenticate the user. If they are correct, only then his secured information is returned.

The code for the result.aspx page is given below:

The Code

<div id="dbInformation" runat="server">
</div>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        SearchDatabase();
}
void SearchDatabase()
{
    string username = Request.Form["username"];
    string password = Request.Form["password"];
    if ((username == "admin") && 
    (password == "admin"))
        dbInformation.InnerHtml = "Hello admin,
        <br/>Your secured information is given below.............";
    else
        dbInformation.InnerHtml = "Wrong Username or Password. Try again !";
}

Explanation – This .aspx page has a div with id “dbInformation”. Into this div, we will be putting the secured information after authenticating the user. You may also note that this div’s information is loaded by the jQuery Load method located in the login page.

Isn’t this the blueprint of a very simple and highly secured system?

4. Load Data from External Website like Wikipedia

jQuery Load to Fetch Data From Wikipedia

Some websites show information from an external website like Wikipedia. This feature can be easily created using jQuery Load method.

In the jQuery Load method, pass the URL whose HTML is to be fetched, then send it to the server side page (like .aspx or .php). In the server side page, you fetch the HTML of the url and set in the div. Like what we did before, finally we will show that div’s content.

Here, we will be showing this feature in the web page that has 2 checkboxes (for Tom Cruise and Angelina Jolie). On checking any checkbox, the jQuery Load method fetches their information from the Wikipedia page.

The Code

<input type="checkbox" 
id="tomCheckbox" /><label>Show 
"Tom Cruise Information"</label><br />
<input type="checkbox" id="ajCheckbox" />
<label>Show "Angelina Jolie Information"</label>
<div id="externalWebsiteDiv"></div>

$("input[type=checkbox]").change(function () {
    var checkedValue = $(this).prop("checked");
    $("input[type=checkbox]").prop("checked", false);
    $(this).prop("checked", checkedValue);

    if ($("#tomCheckbox").prop("checked") == true) {
        $("#externalWebsiteDiv").load("result.aspx #wikiInformation", 
        { "url": "https://en.wikipedia.org/wiki/Tom_Cruise" }, 
function (response, status, xhr) {
            if (status == "error")
                $("#externalWebsiteDiv").html
                ("Error: " + xhr.status + ": " + xhr.statusText);
        });
    }
    else if ($("#ajCheckbox").prop("checked") == true) {
        $("#externalWebsiteDiv").load("result.aspx #wikiInformation", 
        { "url": "https://en.wikipedia.org/wiki/Angelina_Jolie" }, 
        function (response, status, xhr) {
            if (status == "error")
                $("#externalWebsiteDiv").html("Error: " + 
                xhr.status + ": " + xhr.statusText);
        });
    }
    else
        $("#externalWebsiteDiv").html("");
});

In the server side page, we will fetch the HTML from Wikipedia and set it inside the div.

The Code

<div id="wikiInformation" runat="server">
</div>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string url = Request.Form["url"];
        if (url != null)
            GetWikiData(url);
    }
}

void GetWikiData(string url)
{
    using (WebClient client = new WebClient())
    {
        string htmlCode = client.DownloadString(url);
        wikiInformation.InnerHtml = htmlCode;
    }
}

Conclusion

By now, you may have got a good idea about how useful the jQuery Load function is in the web development tasks. There isn’t any AJAX task that cannot be done without this function. Use it to create powerful AJAX features in your websites.

I hope you enjoyed this tutorial. Please share it on Facebook and Twitter for your friends to know about it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Yogi S.
Software Developer (Senior)
United States United States
Programming is Fun.
I am a Senior Software Developer working in ASP.NET, MVC, C#, jQuery, HTML, Razor and more. I also write programming based tutorials in my own website, codeproject, dzone and few more. Please connect with my social accounts.

Visit my website http://www.yogihosting.com to find many more articles on programming & coding topics.
Thanks !

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionCannot download project Pin
AlainTrépanierQuebec6-Feb-17 7:42
memberAlainTrépanierQuebec6-Feb-17 7:42 
AnswerRe: Cannot download project Pin
Yogi S.6-Feb-17 20:00
memberYogi S.6-Feb-17 20:00 
GeneralMy vote of 4 Pin
gicalle7527-Jan-17 2:21
professionalgicalle7527-Jan-17 2:21 
GeneralRe: My vote of 4 Pin
Yogi S.27-Jan-17 9:18
memberYogi S.27-Jan-17 9:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 7 Feb 2017
Article Copyright 2017 by Yogi S.
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid