Update data on a page without refreshing

This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.

The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:

  • selector the existing HTML element you want to load the data into
  • url a string containing the URL to which the request is sent
  • data (optional) a plain object or string that is sent to the server with the request
  • complete (optional) a callback function that is executed when the request completes

The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.

A visualisation:

visualization

A simple example of using load(), where we load data dynamically when a button is pressed:

DEMO

// no need to specify document ready
$(function(){
    
    // optional: don't cache ajax to force the content to be fresh
    $.ajaxSetup ({
        cache: false
    });

    // specify loading spinner
    var spinner = "<img src="http://i.imgur.com/pKopwXp.gif" alt="loading..." />";
    
    // specify the server/url you want to load data from
    var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
    
    // on click, load the data dynamically into the #result div
    $("#loadbasic").click(function(){
        $("#result").html(spinner).load(url);
    });

});

If you don’t want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.

To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp

Leave a Comment