How to handle backbone.js model save() to PHP server

Well just as I was making nice progress saving model updates on the client, I ran into an issue: backbone.js by default for mode.save() will call HTTP PUT passing json data. Turns out php cannot handle that so well. 
After checking the php superglobals to no avail, I found this post:  http://www.lornajane.net/posts/2008/Accessing-Incoming-PUT-Data-from-PHP

Using this approach, I actually got the server side code to work and handle the default backbone.js model.save(). However its a bit convoluted and took some time to work it out.

I think the better approach maybe to use a backbone switch as follows: setting Backbone.emulateJSON = true; will cause the JSON to be serialized under a model parameter, and the request to be made with aapplication/x-www-form-urlencoded mime type, as if from an HTML form"
In that case, I can get the "model" param passed, urldecode it, json_decode it and use it as associative array.
*Note: I since saw in backbone.js code comments that emulateJSON = true; seems to be the preferred approach for PHP. That's what I'm using/

All in all, one of those learning excursions you get when using something new like backbone.js.

Both versions of code for Alternative 1 and 2 are below.

onwards...

Alternative 1:

parse_str(file_get_contents("php://input"),$post_vars);

// should return HTTP error code here if true
if (!isset($post_vars) || count($post_vars) <= 0) {
return ;
}
// the json passed is in the FIRST KEY of the array, not the Value! Not as I'd expect...
// So get all the keys from the array and then treat the first one as the json input from the client
//
$keys = array_keys($post_vars);
$str = $keys[0];
// decode that string into an associative array
//
$paramsArray = json_decode($str, true);

if (isset($paramsArray['myParam'])) {
clean it and use it
}


Alternative 2

if (Input::has('model')) {
Logger::log(__METHOD__ . "URL decode only: " . urldecode(Input::get('model')));
$str = urldecode(Input::get('model'));
// decode that string into an associative array
//
$paramsArray = json_decode($str, true);

if (isset($paramsArray['myParam'])) {
clean it and use it

}

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more