Reputation: 4698
I am trying to make a PUT request with jQuery to submit a form that's supposed to create a new REST resource on the server, which returns a 201 Created with a Location header pointing to the newly created resource. Here is the coffeescript code that's supposed to handler the request:
createNewGame = (name) ->
$.ajax({
url: "/games",
type: "PUT",
data: { game: name },
dataType: "json",
success: succ,
error: err})
I can see the request is sent and received with the correct status and Location header set but then nothing happens:
The response:
Server Warp/0.4.5
Set-Cookie Game=game123; HttpOnly
Location http://localhost:5678/resources/html/game.html
Content-Type application/json
Transfer-Encoding chunked
The request:
Host localhost:5678
User-Agent Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en,en-us;q=0.8,fr;q=0.5,fr-fr;q=0.3
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:5678/resources/html/index.html
Content-Length 12
If I use a 302 response, then jQuery follows the response's Location header but then how am I supposed to tell the page to load the page pointed at in the answer? Of course, I could use a different mechanismm (eg. a POST query) and I know my request is not REST compliant as the url for the request should point at a specific resource, yet I would like to understand better the issue as I think PUT is the correct verb here (I can construct on the client siide the URI for the resource to create).
Thanks for answering.
Upvotes: 1
Views: 1283
Reputation: 1689
You can redirect the user within the success function (via javascript's window.location.href()
).
More importantly, in this case I think POST
is more appropriate than PUT
. POST
is used to create new resources, while PUT
is used to create or update named resources.
Since you are not naming the resource directly, you should be using: POST /games
. Otherwise, you probably want to use something like: PUT /game/unique-name
.
See also this SO answer for a good summary of POST
vs PUT
.
Upvotes: 1