If you’ve designed a web service for other HTTP clients, you’ve used PUT and DELETE as well.
What are these methods?
HTTP PUT and DELETE are used in REST (software architectural style) for content.
Are they allowed as HTML Form methods?
No, only methods that are allowed in HTML forms are POST and GET.
What happens if I use other than POST and GET as an HTML form method?
Browser doesn’t complain but it will be sent as GET request.
Can I make a PUT and DELETE requests from an HTML form?
- If the server is Restful architecture then hopefully there could be a work around provided to override methods, if not create a override.
1. XMLHttpRequest req:
Below is a pure JS function that makes a PUT request to the server. You can use jQuery’s AJAX method which is more usable and simplified form that wraps
XMLHttpRequest raw browser object.
https://gist.github.com/pasupulaphani/8402603?file=makePutReq.js > -> Please make sure that the server has given you permissions to use these methods. You can verify them by making an OPTIONS request and looking into Access-Control-Allow-Methods option values. > -> For Cross-Origin Resource Sharing (CORS) look at origin options (Access-Control-Allow-Origin). See HTML 5 Rocks Tutorial on CORS for a quick look and here is full spec.
2. Server with Restful architecture:
REST service is based on HTTP protocol nevertheless is just a set of conventions about how to use HTTP. All modern web frameworks provide us with handlers for HTTP method override which makes web API easier and cleaner. Lets see how they are implemented in few major web frameworks.
Expressjs is based on REST architecture and provides us with an handler for method override.
- Add this line
app.use(express.methodOverride())to your middleware configuration.
app.putfor PUT and
app.deletefor DELETE in your routes and change their respective handlers if you have controllers setup.
- Add an hidden input element with name “_method” to your form with the CURD action as its value.
Rails accepts a POST request and looks for a :method parameter; assuming it is a default scaffold, PUT gets routed to update controller def; similarly DELETE gets routed to destroy controller def.