1. Making a GET Request:
$.ajax({
url: 'YourAPIEndpoint',
type: 'GET',
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
2. Making a POST Request:
$.ajax({
url: 'YourAPIEndpoint',
type: 'POST',
data: { key1: value1, key2: value2 },
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
3. Sending JSON Data:
$.ajax({
url: 'YourAPIEndpoint',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ key1: value1, key2: value2 }),
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
4. Handling Authentication:
$.ajax({
url: 'YourAPIEndpoint',
type: 'GET',
headers: {
'Authorization': 'Bearer ' + token
},
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
5. Using Deferred Objects (Promises):
var request = $.ajax({
url: 'YourAPIEndpoint',
type: 'GET'
});
request.done(function(response) {
// Handle successful response
});
request.fail(function(xhr, status, error) {
// Handle error
});
6. Setting Timeout:
$.ajax({
url: 'YourAPIEndpoint',
type: 'GET',
timeout: 5000, // milliseconds
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
7. Handling Cross-Origin Requests (CORS):
$.ajax({
url: 'YourAPIEndpoint',
type: 'GET',
crossDomain: true,
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});
8. Uploading Files with AJAX:
var formData = new FormData();
formData.append('file', $('#fileInput')[0].files[0]);
$.ajax({
url: 'YourAPIEndpoint',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
// Handle successful response
},
error: function(xhr, status, error) {
// Handle error
}
});