jQuery - Load

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.

https://www.w3schools.com/jquery/jquery_ajax_load.asp

$(selector).load({url},{data},{callback});
  • 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
Simple Test

 

It is also possible to add a jQuery selector as part of the URL selector argument. The following example loads the content of SampleFile.txt with id="special" into the UI card.


$(document).ready(function () {
    $("#btnDemo").click(function () {
        $("#demo1").load("https://city-info-api-prod.azurewebsites.net/api/v1.0/cities?pageNumber=1&pageSize=10");
    });

    $("#btnDemo2").click(function () {
        $("#demo1").load("../../assets/SampleFiles/SampleFile.txt #special");
    });

    $("#btnDemo3").click(function () {
        $("#demo2").load("ajax-sample.txt", function (responseTxt, statusTxt, xhr) {
            if (statusTxt == "success") { alert("External content loaded successfully!"); }

            if (statusTxt == "error") { alert("Error: " + xhr.status + ": " + xhr.statusText); }
        });
    });

});

 

The CallBack parameter

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.


$("#btnDemo3").click(function()
{
    $("#demo2").load("ajax-sample.txt", function(responseTxt, statusTxt, xhr)
    {
        if(statusTxt == "success")
        {alert("External content loaded successfully!");}

        if(statusTxt == "error")
        {alert("Error: " + xhr.status + ": " + xhr.statusText);}
    });
});