Complete Guide to Sending PUT and DELETE Requests in jQuery

Nov 08, 2025 · Programming · 16 views · 7.8

Keywords: jQuery | AJAX | PUT Requests | DELETE Requests | HTTP Methods

Abstract: This article provides a comprehensive guide on sending PUT and DELETE requests in jQuery using the $.ajax() method for updating and deleting server resources. It covers basic syntax, parameter configuration, data transmission methods, practical application scenarios, and offers in-depth analysis of data passing issues in DELETE requests along with compatibility solutions and best practices.

Overview of HTTP Request Methods in jQuery

In web development, interacting with servers for data exchange is a common requirement. jQuery provides various convenient methods to handle HTTP requests, with $.get() and $.post() being the most frequently used for GET and POST requests respectively. However, for PUT and DELETE requests, which are equally important in RESTful API design, jQuery does not offer corresponding shortcut methods.

GET requests are typically used for retrieving data, while POST requests create new resources. PUT requests update existing resources, and DELETE requests remove resources. These HTTP methods collectively form the core operations of REST architecture.

Sending PUT/DELETE Requests Using $.ajax() Method

Although jQuery lacks dedicated $.put() or $.delete() methods, these requests can be implemented using the universal $.ajax() method. The $.ajax() method provides comprehensive configuration options to meet various complex request requirements.

Basic PUT request example:

$.ajax({
    url: '/api/users/123',
    type: 'PUT',
    data: {
        name: 'John Doe',
        email: 'john@example.com'
    },
    success: function(response) {
        console.log('User updated successfully');
        // Process response data
    },
    error: function(xhr, status, error) {
        console.error('Update failed:', error);
    }
});

DELETE request configuration is similar:

$.ajax({
    url: '/api/users/123',
    type: 'DELETE',
    success: function(response) {
        console.log('User deleted successfully');
        // Handle post-deletion logic
    },
    error: function(xhr, status, error) {
        console.error('Deletion failed:', error);
    }
});

Data Passing Issues in DELETE Requests

In practical development, data transmission in DELETE requests involves some controversy and compatibility issues. According to HTTP specifications, the DELETE method primarily removes resources identified by the request URI, but the specification does not explicitly prohibit including data in the request body.

Throughout jQuery's version history, the behavior of data transmission in DELETE requests has undergone multiple changes. In some versions, data set via the data parameter was automatically converted to URL query parameters, while in other versions, data was placed in the request body.

Consider this example:

// This approach may not correctly transmit data in certain environments
$.ajax({
    url: '/api/users',
    type: 'DELETE',
    data: { id: 123 }
});

To address compatibility issues, consider these alternative approaches:

// Option 1: Manually construct URL parameters
$.ajax({
    url: '/api/users?id=123',
    type: 'DELETE'
});

// Option 2: Use custom request headers
$.ajax({
    url: '/api/users/123',
    type: 'DELETE',
    headers: {
        'X-User-Id': 123
    }
});

Practical Application Scenarios and Best Practices

In real-world projects, PUT and DELETE requests are commonly used for RESTful API interactions. For example, in user management systems:

// Update user information
function updateUser(userId, userData) {
    return $.ajax({
        url: '/api/users/' + userId,
        type: 'PUT',
        data: JSON.stringify(userData),
        contentType: 'application/json',
        dataType: 'json'
    });
}

// Delete user
function deleteUser(userId) {
    return $.ajax({
        url: '/api/users/' + userId,
        type: 'DELETE'
    });
}

To ensure code robustness, consider adding error handling and timeout settings:

$.ajax({
    url: '/api/resource',
    type: 'PUT',
    data: updateData,
    timeout: 10000, // 10-second timeout
    success: function(response) {
        // Handle successful response
    },
    error: function(xhr, status, error) {
        if (status === 'timeout') {
            alert('Request timeout, please try again');
        } else {
            alert('Operation failed: ' + error);
        }
    }
});

Compatibility Considerations and Alternative Approaches

Given varying server and environment support for DELETE request bodies, it's advisable to establish a unified data transmission strategy early in the project. If the server strictly adheres to certain specifications (such as some cloud service providers rejecting DELETE requests with bodies), URL parameters should be used instead.

For scenarios requiring complex data transmission, consider using POST method with custom headers to simulate DELETE operations:

$.ajax({
    url: '/api/users',
    type: 'POST',
    data: {
        _method: 'DELETE',
        id: 123,
        additionalData: 'some value'
    }
});

This approach requires corresponding server-side support to parse the _method parameter but offers greater flexibility in data transmission.

Conclusion

Through the $.ajax() method, developers can flexibly send PUT and DELETE requests to implement complete RESTful operations. Although jQuery doesn't provide dedicated shortcut methods, the rich configuration options of $.ajax() are sufficient for various complex requirements. In practical development, special attention should be paid to compatibility issues with data transmission in DELETE requests, and appropriate data transmission strategies should be selected based on project needs.

As modern web development evolves, while new technologies like Fetch API have emerged, jQuery's AJAX functionality continues to play an important role in many projects due to its excellent browser compatibility and concise API design. Mastering the proper use of these HTTP request methods is crucial for building robust web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.