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

Detecting system dark mode in CSS

css


The "dark mode" feature has been spreading to apps and websites far and wide recently. It brings a new and discrete look to your applications as well as offering some extra control to the user...

CSS Material design toggle switch

html - css - javascript


Because sometimes all you want is just a good looking switch without importing an entire library to do it.

Immersive Parallax scrolling effect

javascript - css - html


You might have noticed while moving along in a car or train, how far away objects seem to move across your vision slower than those closer to your eyes. This effect is known as parallax and its a fundamental aspect of vision which can often go unnoticed.