AJAX Structure with JQuery in JavaScript for Making a POST Call

Tiempo de lectura: 2 minutos

In this example, I’m going to show a basic structure for making a POST type AJAX request with jQuery in JavaScript.

First, we define the parameters of the AJAX request. Here, we set the URL to which we’ll send the request, the type of request which will be POST, and the type of data (in this case, JSON).

$.ajax({
  url: 'https://example_devcodelight.com/api', // URL of the request
  type: 'POST', // Type of request
  dataType: 'json', // Type of data 
  data: { // Data to send in the request (if necessary)
    key1: 'value1',
    key2: 'value2'
  },

Then if the request is successful, the success function will be executed. Here, the response from the server is received and the received information can be processed. In this example, we’ll display the response in the browser console.

success: function(response) {
  console.log('Successful response:', response);
  // Here you can process the received data
},

In case the request fails, the error function will be executed. This allows handling errors properly. In the example, the error message is displayed in the browser console.

error: function(xhr, status, error) {
  console.error('Error in request:', status, error);
  // Here you can handle the error appropriately
},

The complete AJAX structure looks like the following as I show below.

$.ajax({
  url: 'https://example_devcodelight.com/api', // URL of the request
  type: 'POST', // Type of request
  dataType: 'json', // Type of data 
  data: { // Data to send in the request (if necessary)
    key1: 'value1',
    key2: 'value2'
  },
  success: function(response) {
    // Function handling successful response
    console.log('Successful response:', response);
    // Here you can process the received data
  },
  error: function(xhr, status, error) {
    // Function handling errors during the request
    console.error('Error in request:', status, error);
    // Here you can handle the error properly
  }
});

I hope this helps. Have a great day!

Leave a Comment