To return data after an AJAX call success in jQuery, you can use the success function or use the promise method.
Here's an example using the success function:
$.ajax({
url: 'example.com/ajax',
data: { param1: 'value1', param2: 'value2' },
dataType: 'json',
success: function(data) {
// This code will be executed when the AJAX call is successful
console.log(data);
// You can do something with the data here
},
error: function(jqXHR, textStatus, errorThrown) {
// This code will be executed if the AJAX call fails
console.error(errorThrown);
}
});
In this example, we're making an AJAX call to example.com/ajax with two parameters param1 and param2. We've set the dataType to 'json' so that the response data is parsed as JSON.
Inside the success function, we can access the returned data object and do something with it. In this example, we're logging the data to the console.
If the AJAX call fails, the error function will be executed instead. The jqXHR object contains information about the error, such as the HTTP status code and the error message.
Alternatively, you can use the promise method to return data after an AJAX call success. Here's an example:
const ajaxPromise = $.ajax({
url: 'example.com/ajax',
data: { param1: 'value1', param2: 'value2' },
dataType: 'json'
});
ajaxPromise.done(function(data) {
// This code will be executed when the AJAX call is successful
console.log(data);
// You can do something with the data here
}).fail(function(jqXHR, textStatus, errorThrown) {
// This code will be executed if the AJAX call fails
console.error(errorThrown);
});
In this example, we're creating a Promise object with the $. ajax () method and storing it in the ajaxPromise variable. We can then use the . done() method to handle the successful outcome and the . fail () method to handle the failed outcome of the promise.