3

I'm setting up a form. All data are retrieved on js file. How can I send this data to a symfony controller ?

I have tried : $request->get('values'); and $request->request->all(); but none of this actually works.

Controller PHP :

    /**
     * @Route("/dem", name="dem")
     */
    public function index(Request $request)
    {
       if (isset($request->isXmlHttpRequest())) {
          dump(json_decode($request->get('values')));
       }
       return $this->render('dem/index.html.twig');
    }

JS File :

   console.log(values) // response: json of an array of elements 
   $.ajax({
      method: "POST",
      url: url,
      data: {values: values},
      success: data => {
         console.log('data : ');
         console.log(data);
      }
   });

HTML Form :

    <form id="dem" name="dem" action="{{ path('dem') }}" method="POST" class="w-75 m-auto">

I expect an output of my array of elements

Thx all :}

1
  • try to display -- dump(json_decode($request->request->get('values'))); Commented Apr 26, 2019 at 14:31

2 Answers 2

2

Maybe you can use $request->getContent();, it return the raw json of your request. After you have to unserialize it.

$parametersAsArray = [];
if ($content = $request->getContent()) {
    $parametersAsArray = json_decode($content, true);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Good idea, i just tried that but no result $request->getContent() is empty
If you add to your request this HEADER 'Content-Type': 'application/json'
where do you want to add this line ? before the dump ?
in your js file
1

Your code seems correct in controller. Although, you have to do some minor changes in your js file:

$.ajax({
                        url: url,
                        data: {
                            values: values
                        },
                        type: 'POST',
                        dataType: "json",
                        success: function (data) {
                           console.log('data : ');
                           console.log(data);
                        }

Comments

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.