Examples of Ajax requests with jQuery

jQuery simplifies our life a lot, even with Ajax requests, here’s an example of a basic request:

$.ajax({
  url: 'myfile.php',
  success:function(data){
    alert(data);
  }
});

This is the simplest possible Ajax request, if our request is successful, the success function will be executed. In our case will perform an alert of the content of the myfile.php page saved in the date variable.

Obviously, Ajax requests in jQuery also accept other options, for example you can choose whether to use GET or POST method, you can pass parameters, ignore the cache, manage if the request went wrong and so on …

Here are some examples:

Ajax request in POST with parameters:

$.ajax({

  url: 'myfile.php',
  type: 'POST',
  data: { id: '7', name: '.Maui' },
  
  success:function(data){
    alert(data);
  }

});

Ajax request ignoring the cache:

$.ajax({
  url: 'myfile.php',
  cache: false,
  success: function(data){
    alert(data);
  }
});

Request with error handling:

$.ajax({
  url: 'myfile.php',
  cache: false,
  success:function(data){
    alert(data);
  },
  error: function (request, status, error) {
        alert('Attention, the following error occurred: ' + error);
  }
});

Synchronous Ajax request:

$.ajax({
  url: 'myfile.php',
  async: false,
  success: function(data){
    alert(data);
  }
});

If the async parameter is not specified, the request will be asynchronous, because the default value of async is true.

Leave a Comment

Your email address will not be published. Required fields are marked *