Wednesday, September 10, 2014

201 or 303

Post/Redirect/Get is a common pattern to create a new resource and then load the representation of the new resource in browser. An advantage of this pattern is to prevent duplicate form submission when a user clicks the browser refresh button after the Post request. The response code of the Post request is 303 if the request is successful. The browser will always redirect to the Location link in the 303 response header.

Unfortunately, this behavior can be confusing when the Post request is sent via AJAX. That means JavaScript will see response code 200 directly instead of 303 when the Post is successful. The AJAX engine inside a browser has no way to stop at the 303 and prevent the redirection. Furthermore, JavaScript will normally see the HTML representation of the new resource in the response. This can be confusing when you want to control what the page to do when the new resource is created and load the JSON representation of the new resource. In this case, 201 is obviously better than 303, because the JavaScript can decide how to notify the user and also furthermore how to load the new resource into the current page or redirect.