6

Via jquery, I ajax/POST this json

{"indices":[1,2,6]}:

to a symfony2 action. Right now I only really care for the array, so if this makes things considerably easier I could just post [1,2,6] as well.

How can I convert this to a php object?


Somehow, this does not work:

/**
 * @Route("/admin/page/applySortIndex", name="page_applysortindex")
 * @Method("post")
 * @Template()
 */
public function applySortIndexAction()
{
    $request = $this->getRequest();
    $j = json_decode($request->request->get('json'));
    $indices = $j->indices;
    return array('data'=> $indices);
}

gives a

Notice: Trying to get property of non-object in .../PageController.php line 64 (500 Internal Server Error)

which would be where I access $j->indices, where $j seems to be null


The poster:

$.ajax({
      type: 'POST',
      url: "{{ path('page_applysortindex')}}",
      data: $.toJSON({indices: newOrder}),
      success: ...
5
  • I guess you didn't use "json" as a name for this POST-parameter Commented Sep 9, 2011 at 11:25
  • I am not actively using any name at all, I'll post the js above... Commented Sep 9, 2011 at 11:30
  • Ah, so I have to write data: "data=" + $.toJSON({indices: newOrder}) and all is well. Probably there is a nicer solution for this. Commented Sep 9, 2011 at 11:37
  • you send a POST request but the JSON you send in the body, have look at my third edit Commented Sep 9, 2011 at 11:38
  • +1 for interesting question ... was wondering about that myself earlier that day Commented Sep 9, 2011 at 11:50

1 Answer 1

5

To get the data sent via body use:

$request = $this->getRequest();
$request->getContent();

inspect the output and then act upon. but this will contain the json.

(yep, tested it. this leads to your json)


getting a POST-parameter with name json from within a controller:

$request = $this->getRequest();
$request->request->get('json');

Request-object


$j = json_decode('{"indices":[1,2,6]}');

var_dump($j);

leads to:

object(stdClass)#1 (1) {
  ["indices"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(6)
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! Things can be so easy if you can ask the right guy :)
Arrgh, but how do I get to the json from the request?
I cannot seem to get to the json, still. I updated my question to show the actual method in question...
$json = json_decode($request->getContent(), true); - the true decodes your json to an array instead of a stdObj.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.