I am trying to send post data using fetch in twig. But I can not access to those variables in the controller.
here my fetch
let response = await fetch(baseUrl + '/aaa/nom-de-levenement/add', { method: 'POST', headers: { 'X-CSRF-TOKEN': token, "Content-type": "application/json", }, body: { "page": "pageName" } }) return response.json()
and my controller :
/** * @Route("/add", methods={"POST"}) */ public function createPage($slug, EntityManagerInterface $entityManager, EventRepository $eventRepository, Request $request){ $event = $eventRepository->findOneBy(['slug' => $slug]); $data = $request->request->get('page'); dd($data); }
And the dump returning null
Thank you for help
I tryied to change the content type in fetch dans some things in the controller for exemple :
$_POST return null
$request->get(‘page’) return null
I try the controller using postman, and it return the good variable.
Advertisement
Answer
To send POST data that way you should use FormData
object:
const data = new FormData(); data.append('page', 'pageName'); let response = await fetch(baseUrl + '/aaa/nom-de-levenement/add', { method: 'POST', headers: { 'X-CSRF-TOKEN': token, "Content-type": "application/json", }, body: data }) return response.json()
Then you could do that in your controller:
$data = $request->request->get('page');
If you try to pass “raw” data in body
, you can access it using $request->getContent()
method, but I believe in this case that will return "[object Object]"
because the body
object will be simply parsed to string.