Skip to content

Instantly share code, notes, and snippets.

@MarshalOfficial
Created May 11, 2024 05:57
Show Gist options
  • Save MarshalOfficial/1a25a122c97dbc1f73c2019f587ac472 to your computer and use it in GitHub Desktop.
Save MarshalOfficial/1a25a122c97dbc1f73c2019f587ac472 to your computer and use it in GitHub Desktop.
jquery ajax handy cheat sheet

jQuery AJAX Cheat Sheet

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
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment