To send JSON data in an AJAX POST request with jQuery, you can use the $.ajax()
or $.post()
methods. Here's an example using the $.ajax()
method:
var data = {
name: 'John',
age: 30,
email: '[email protected]'
};
$.ajax({
url: '/your-url',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(response) {
console.log('Success:', response);
},
error: function(xhr, status, error) {
console.log('Error:', error);
}
});
In this example, the data
object is serialized to a JSON string using JSON.stringify()
. The dataType
property is set to json
to indicate that the expected response is in JSON format. The contentType
property is set to 'application/json'
to specify the content type of the request.
You can also use the $.post()
method, which is a shorthand method for the $.ajax()
method when performing POST requests:
var data = {
name: 'John',
age: 30,
email: '[email protected]'
};
$.post('/your-url', JSON.stringify(data), function(response) {
console.log('Success:', response);
}, 'json')
.fail(function(xhr, status, error) {
console.log('Error:', error);
});
In this example, the $.post()
method is used to send the POST request, and the dataType
parameter is set to 'json'
.
Remember to include the JSON.stringify()
function to convert the JavaScript object to a JSON string before sending the request.