Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I use Silex in conjunction with Backbone.js for one of my personal projects (AtariGamer.com). Both of the frameworks are great and work very well together and are generally very well documented. However, they don't prevent silly mistakes from creeping into your code. This was one of them.

The issue I was seeing was that when I was calling Model.destroy() the error callback was being invoked every single time even on successful deletes. I confirmed that I was in fact getting a DELETE request on the Silex end, and that the deletion was being processed successfully. I figured that since the framework was doing everything right, I must have been doing something wrong.

After a bit of investigation I tracked down and fixed the issue. The problem was with the function that was handling the DELETE request. Specifically it was with the Response object it was returning. The original return statement looked like this...
return new Response('', Response::HTTP_OK);

In hindsight the issue should have been obvious immediately. The HTTP_OK (200) code has this requirement:
Aside from responses to CONNECT, a 200 response always has a payload, though an origin server MAY generate a payload body of zero length. If no payload is desired, an origin server ought to send 204 No Content instead.

I guess Backbone.js is strict about the payloads it receives if the status is 200. There were two possible solutions to this...

One solution - use code HTTP_NO_CONTENT (204) instead of 200...
return new Response('', Response:: HTTP_NO_CONTENT);

Another solution - return an empty JSON object as the payload...
return new Response('{}', Response::HTTP_OK);

The error in Backbone.js occured because it was trying to parse the response body as a JSON object whenever it saw a status of 200. So, using either the 204 status or an empty JSON object made it work as expected.

I opted for the second solution but both are valid.


A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.