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

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.

Handy Python tricks for beginners

python


When first starting out in a language like Python, things tend to move a bit slow until you learn how to use the built-in functions and operators which exist to speed up the development process. So this tutorial will try to mitigate that problem.

Five practical .htaccess tricks

apache - php


Apache's '.htaccess' has some very powerful tools that you can use with minimal effort to enhance the user experience and even performance, of your website.