0

This might seem like an unordinary json question but I can assure you I couldn't find an answer to my problem.

In the code example below I would like to get (possibly decode the json data that is being transferred. I've tried json_decode($_POST). By the way the request type is POST. Is there anyway I can obtain the json data into an array or a variable so when I would like to call name or age I will easily retrieve them from request?

I'm following a backbone.js tutorial and here is my model;

<script type="text/javascript">
        var URL=Backbone.Model.extend({
            initialize: function()
            {
                console.log("URL has been initialized");
            },
            defaults:{
                name:'not defined',
                age:'not defined'
            },
            urlRoot:"/Backbone/manage.php",
            url:function(){
                var base = this.urlRoot || (this.collection && this.collection.url) || "/";
                console.log("Base has been produced");
                if(this.isNew()) return base;

                return base+"?id="+encodeURIComponent(this.id);
            }
        });

        var url=new URL({name:"John",age:10});
        url.save();
    </script>

Later on I use Google Chrome in order to watch the network and I can clear see that the data is passed as form data. Here is the result in Google's Network Tool;

model:{"name":"John","age":10}
Ali
  • 5,338
  • 12
  • 55
  • 78
  • Use `print_r($_POST);` to see which field name carries the payload, if any. It doesn't just show up as `$_POST` with raw data. It would be `json_decode($_POST["varname"])` (e.g. `"id"`, but that's your issue) or possibly reside in `php://input`. – mario May 17 '12 at 22:53

2 Answers2

2

If you are getting JSON payload as raw post data you can read it with:

json_decode(file_get_contents('php://input'));

You could also read it from $HTTP_RAW_POST_DATA if php.ini settings allow for that variable do be filled.

Since what you are getting is:

model=%7B%22name%22%3A%22John%22%2C%22age%22%3A10%7D

You can't directly decode it as JSON because it's not valid JSON.

So try:

parse_str(file_get_contents('php://input'), $post);
$myObject = json_decode($post['model']);
Kamil Szot
  • 17,436
  • 6
  • 62
  • 65
  • Thanks for the response. I've tried `$modelData=json_decode(file_get_contents('php://input')); echo "Name : ".$modelData->name;` but it didn't work – Ali May 17 '12 at 23:03
  • try `var_dump($modelData);` it may be something different from what you expect. Also try `var_dump(file_get_contents('php://input'))` to see if you are getting anything at all – Kamil Szot May 17 '12 at 23:06
  • I've tried the last edit you did and it prints nothing. Both tried '$myObject->name' and '$myObject[0]->name' – Ali May 17 '12 at 23:16
  • Have you tried to `var_dump(file_get_contents('php://input'))` ? If it shows you nothing or NULL any further code is not even worth trying because you are not getting any data. Have you tried displaying what your script has in $HTTP_RAW_POST_DATA ? – Kamil Szot May 17 '12 at 23:18
  • Tried it right now. It prints: string(52) "model=%7B%22name%22%3A%22John%22%2C%22age%22%3A10%7D" – Ali May 17 '12 at 23:21
  • Latest Update: I've commented my emulateJSON and emulateHTTP codes and I've used `var_dump(file_get_contents('php://input'))` which resulted as 'string(24) "{"name":"John","age":10}" '. – Ali May 17 '12 at 23:33
1

You'll need to do json_decode on the model key of the $_POST array. The model key contains the json string that you need to decode.

$modelData = json_decode($_POST['model']);

Then you can access the data like $modelData->name or $modelData->age;

EDIT:

Try adding this to your backbone set up:

Backbone.emulateHTTP = true;
Backbone.emulateJSON = true;

This will make it so you are getting application/x-www-form-urlencoded instead of application/json. This should then populate your $_POST array correctly.

See here for explanation: http://documentcloud.github.com/backbone/docs/backbone.html#section-162

Gohn67
  • 10,608
  • 2
  • 29
  • 35
  • Thanks a lot for the idea. It seemed quite reasonable to me too thus I've tried: `$modelData = json_decode($_POST['model']); echo "Name : ".$modelData->name;` but didn't work – Ali May 17 '12 at 23:05
  • 1
    What does print_r on your $_POST variable give you? – Gohn67 May 17 '12 at 23:08
  • it prints 1 and somehow now I can get a type 'Array ( [model] => {\"name\":\"John\",\"age\":10} )' with @Kamil Szot's solution – Ali May 17 '12 at 23:13
  • Interesting. I wonder why your Post array is not populating correctly. Does populate correctly with a regular form post? – Gohn67 May 17 '12 at 23:16
  • http://stackoverflow.com/questions/7530862/cant-get-jquery-ajax-post-to-work. Maybe that is the reason. – Gohn67 May 17 '12 at 23:18
  • You may need to turn use `Backbone.emulateHTTP`, so it will send requests `application/x-www-form-urlencoded` as `application/json` – Gohn67 May 17 '12 at 23:20
  • @rolandbishop. That's called magic quotes. And there is no need for lengthy poking-in-the-dark-chats here on Stackoverflow. Post relevant information with your question next time. – mario May 17 '12 at 23:21
  • @Gohn67 I've did everything your edit and written `$modelData = json_decode($_POST['model']); if($modelData==NULL) echo "Fail"; else echo "Success";` which outputted 'Fail' – Ali May 17 '12 at 23:36