2

I have an ajax request working fine. My problem is I do not really know how to use correctly my controller to get the datas in the format I would like.

I would like to use this kind of method:

$request->request->get('pseudo'); // will return "bob"

Here is my controller code:

public function mainPlayAction(Request $request)
{

    if ($request->isXmlHttpRequest())
    {
        $allContent = $request->getContent(); // will return a string with this format "selectedBalls=34&selectedStars=11"

        $selectedBalls = $request->request->get('selectedBalls'); // will return null

        $selectedstars= $request->request->get('selectedStars'); // will return null

        $all = $request->request->all(); // will return Array[0]

        $response = [
            'allContent' => $allContent,
            'selectedballs' => $selectedBalls,
            'selectedStars' => $selectedStars,
            'all' => $all,                
            'success' => true,
            "status" => 100
        ];

        return $this->json($response);
    }
}

Here is my ajax code

$.ajax({
    url: url,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    type: "POST",
    data: {
        'selectedballs': selectedBalls,
        'selectedStars': selectedStars,
        'countGames': countGames
    },
    success: function (response) {
        window.console.log(response);
    },
})
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
zm455
  • 489
  • 11
  • 26

2 Answers2

4

You simply need to call ->get() on Request object to get the data passwed along with AJAX Request.

Like this,

$selectedballs=$request->get('selectedballs');
$selectedStars=$request->get('selectedStars');
$countGames=$request->get('countGames');
Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

I found a good answer.

I deleted this line of code from my ajax request

contentType: "application/json; charset=utf-8"

And now I can retrieve my datas using

$request->get('selectedBalls');
zm455
  • 489
  • 11
  • 26
  • 1
    When you get a chance, read up a bit on the difference between posting json and posting form data. Your solution is not sustainable. – Cerad Aug 13 '16 at 11:54
  • I mad a mistake in my solution and I edited it. Now i use $request->get('selectedBalls') . According to you isn't it a good solution ? Note: I send ajax datas without using any form. – zm455 Aug 13 '16 at 11:58
  • Read the answer in the link I gave you. In particular, look at how $content is used. – Cerad Aug 13 '16 at 12:27
  • Sorry. I have tried since 30 min to implement the solution of the link you posted. But I'm not able to implement it. Using the function $request->getcontent() returns me a string "url encoded" like "id=34&pseudo=bob" . . . and then sure ... json_decode function doesn't works on that string format. – zm455 Aug 13 '16 at 13:13