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

Responsive web design guide

css - html


In 2017 it was recorded that around 63% of all U.S web traffic is made up of mobile devices. It is becoming increasingly vital that websites adopt a responsive design to accommodate this rapidly growing portion of the market.

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.

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.