How to use jQuery's ajax to load dynamic content

01 Dec, 2018

Providing dynamically loaded content instead of loading a whole new page can go a long way in terms of improving the experience your users have on your website. jQuery's $.ajax() function provides a relatively simple way to do just that.

The way Ajax works is it will load a set page and return the contents into a variable. Quite a simple, however, the possibilities for what can be accomplished with it are huge. jQuery's $.ajax() function allows 'post' and 'get' variables to be sent through with the request, and the pages will be loaded as if the user did themselves, so any current sessions will stay active through ajax. This allows you to customise the ajax content to the user loading it.

Heres an example of how ajax could be used to dynamically show a users search results.


var pageNumber = 1;
$.ajax({
  type: 'post',
  url: 'ajax_results.php',
  data: {
    //format "variableNameToSend: valueToSet"
    query:'funny cats',
    page:pageNumber
  },
  error: function() {
    console.log("An error has occurred :(");
  },
  success: function (response) {
    //do somthing with response eg:
    $('#output').html(response);
  }
});
		

Heres a simplified example of how 'ajax_results.php' might behave


if(isset($_POST['query']) && isset($_POST['page'])){
  // EXAMPLE { results = Query database for results with $_POST['query'] and page offset of $_POST['page']; }
  foreach($results as $result){
    echo $result . "\n";
  }
}
		

This is just one of many possible uses for Ajax. In some situations, you might want to return the results as JSON so that you have more freedom to manipulate the results on the client side. In that case, there is an extra datatype parameter that can be added to the ajax function for parsing JSON.


dataType: 'jsonp'
		

Other Tutorials

View All

Local Storage vs Cookies (The storage showdown)

javascript


Local site storage can open up a ton of possibilities in web design and breath new life into an otherwise static web page. Whether you want to do something simple like "show a welcome message only once", or something more complex.

Triggering vibrations from your website

javascript


Most common mobile browsers (excluding safari) allow you to trigger the device's vibration motor from your web application using the Vibration API. The Vibration API is provided to you by the mobile browser itself.

Using variables in CSS

css - javascript


When styling your web app, you've probably found yourself copying hex colour codes, margin parameters or other styles to several elements to achieve a consistent design across your app.