4

I'm using Backbone, PHP(5.6) and Apache(2.4).

Problem: When posting data using Backbone's model.save() the $_POST array is empty on the server.

I know about different ways to fix this.

Client way: setting Backbone.emulateJSON to true or changing the Backbone source.
Server way: reading raw body instead of $_POST.

These work but they feel like hacks and in fact they end up being a bit inconvenient.
Also, Backbone's doc says:

If you're working with a legacy web server that can't handle requests encoded as application/json, setting Backbone.emulateJSON = true; will [fix it].

So it sounds like a server problem. How do I make my server non-legacy?

SQL.injection
  • 2,607
  • 5
  • 20
  • 37
galki
  • 8,149
  • 7
  • 50
  • 62
  • Is this because you can't handle PUT and DELETE methods? possible duplicate http://stackoverflow.com/questions/9816274/ways-to-save-backbone-js-model-data – OIS Jul 09 '15 at 09:01
  • thanks but I don't believe it's related. – galki Jul 09 '15 at 09:04
  • Did you check $_SERVER['REQUEST_METHOD'] ? If it's not POST I don't think $_POST will populated. – OIS Jul 09 '15 at 09:06
  • the request method is recognized as POST but the array is empty – galki Jul 09 '15 at 09:09
  • 1
    @galki There's no built-in way in PHP to access a JSON post (besides reading the raw data). Either use a library/framework like Symfony to do the work or roll your own solution http://stackoverflow.com/questions/10930789/insert-backbone-js-model-into-mysql-database/10931092#10931092 – nikoshr Jul 09 '15 at 09:11
  • 1
    PHP does not handle Content-Type: application/json afaik. - see [here](http://stackoverflow.com/questions/7047870/issue-reading-http-request-body-from-a-json-post-in-php) and [here](http://stackoverflow.com/questions/21441786/post-to-php-from-node-js) - some Request handlers like in Symfony 2 seems to handle it though iirc. – OIS Jul 09 '15 at 09:14
  • Thank you! I must have misinterpreted the 'legacy web server' comment and this is correct behavior. – galki Jul 09 '15 at 09:18

1 Answers1

2

Thanks to the comments I realized this is correct behavior.

$_POST is for form data, while json data (application/json) should be gotten from the raw input.

galki
  • 8,149
  • 7
  • 50
  • 62