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

How to center things with CSS

html - css


Being able to center text, divs and images is one of the most important things that you can utilize to create clean and modern websites.

Building a custom chromecast web app

html - javascript


Chromecasts make streaming your favourite songs, games and movies easy. But if you're like me, you might be wondering what's going on behind the scenes when you cast an app, and how you can build your own.

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.