1

I'm using knockout and I'm trying to send information to PHP, using firebug to check Network -> Headers I have this:

Request URL:http://localhost/loyalty/welcome/json/
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:85
Content-Type:application/json
Host:localhost
Origin:http://localhost
Referer:http://localhost/loyalty/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.46 Safari/535.11
X-Requested-With:XMLHttpRequest
Request Payload
{"friends":[{"name":"name","isOnTwitter":false},{"name":"name","isOnTwitter":false}]}
Response Headersview source
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Wed, 15 Feb 2012 11:01:23 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By:PHP/5.3.8

The generated JSON is: {"friends":[{"name":"name","isOnTwitter":false},{"name":"name","isOnTwitter":false}]} and I have no idea how to get those values.

Here is the Ajax call:

save: function() {
        $.ajax({
            url:"http://localhost/loyalty/welcome/json/",
            type: "post",
            data: ko.toJSON(this),
            contentType: "application/json",
            success: function (result) {
                alert(result);
            }
        });

On my CodeIgniter method I have tried to receive it with $this->input->post('friends') and whatever else I could think of and no results.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

4 Answers4

3

change

data: ko.toJSON(this),

to

data: {mydata : ko.toJSON(this) },

In your file which opens up while you post on http://localhost/loyalty/welcome/json/

Read it as:

$myObj = json_decode($_POST['mydata']);

and then you can access your values as:

echo $myObj['friends'][0]['name']; or echo $myObj['friends'][0]['isOnTwitter'];

which will output name or true/false as your json code reads.

EDIT

This thread should help you -> Jquery - How to make $.post() use contentType=application/json?

Community
  • 1
  • 1
linuxeasy
  • 6,269
  • 7
  • 33
  • 40
  • it returns me bool(false) using CodeIgniter, using $_POST[] it returns me "undefined variable: mydata" –  Feb 15 '12 at 11:20
  • did you make the changes as I suggested in the starting part of my answer? – linuxeasy Feb 15 '12 at 11:21
  • yes...and here is the new JSON: mydata={"friends":[{"name":"João","isOnTwitter":false}]} and my php is exactly like yours –  Feb 15 '12 at 11:21
  • correct and then as my answer says, you need to decode the json and access it using a `foreach` or `for loop` or by directly referring to arrays as suits best to you. – linuxeasy Feb 15 '12 at 11:23
  • right...but the problem is that in this line: $myObj = json_decode($_POST['mydata']); I already get a error "undefined index mydata" –  Feb 15 '12 at 11:24
  • ah yah, I have edited my answer, please refer to the javascript part again, this should solve your problem. – linuxeasy Feb 15 '12 at 11:27
  • JSON: mydata=%7B%22friends%22%3A%5B%7B%22name%22%3A%22Jo%C3%A3o%22%2C%22isOnTwitter%22%3Afalse%7D%5D%7D but same error =/ can you continue on chat? –  Feb 15 '12 at 11:30
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/7735/discussion-between-gerep-and-linuxeasy) –  Feb 15 '12 at 11:30
2

I changed the Javascript to this:

$.ajax({
    url:"http://localhost/loyalty/welcome/json/",
    type: "post",
    data: {payload:ko.toJSON(this)},
    success: function (result) {
            t.value = result;
    }
});

Then, in PHP, you can access the JSON via:

<?php json_decode($_POST["payload"]); ?>
wecsam
  • 2,651
  • 4
  • 25
  • 46
  • have idea why that removed line was the problem? –  Feb 15 '12 at 11:45
  • If you don't pass the `data` parameter as an object but as a string, jQuery assumes that you URL-encoded it already, which you hadn't. However, for PHP to read the data, it has to be URL-encoded with a variable name. Writing `data: {payload:ko.toJSON(this)}` told jQuery to URL-encode the JSON automatically and put it in the `payload` variable. – wecsam Feb 16 '12 at 02:25
  • 2
    Sorry, I misread your question. For PHP to read the data, you have to use the MIME type `application/x-www-form-urlencoded`. jQuery uses this by default. Specifying `contentType: "application/json"` overrode that. – wecsam Feb 16 '12 at 02:28
1

As the Content-Type is "application/json" and NOT "application/x-www-form-urlencoded" the $_POST array will be empty.

So, in order to access the JSON payload in a POST request, you have to do this:

$json_data = json_decode(trim(file_get_contents('php://input')), true);    
echo($json_data['param1']);
echo($json_data['param2']);
koxon
  • 818
  • 1
  • 10
  • 12
0

For PHP to get JSON objects you need to use json_decode().

http://php.net/manual/en/function.json-decode.php

Grim...
  • 16,518
  • 7
  • 45
  • 61