I am trying to perform an ajax post request but I can't handle the form.
Ajax :
function ft_postFormation(e) {
e.preventDefault();
data = $('form[name=appbundle_formation_post]').serialize();
$.post({
url: ROOT_DIR + "api/back_office/post_formation",
data: data,
contentType: "application/json",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + $.cookie("token"));
}
}).done(function (e) {
console.log(e);
});
} });
controller :
public function postFormationAction(Request $request)
{
$formation = new Formation;
$form = $this->createForm(FormationForm::class, $formation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
//handling the form
}
}
}
I don't know if I serialize the data correctly or if I do not handle the form correctly. I read this solution everywhere but I am obviously missing something.
I receive the data within the controller (as a string). I also tried to serialize the form with $.serializeArray() but i could not handle the form either.
In all cases $form->getData says the form is correcly created but not filled with the datas received.
I've finally found the problem.
The header was wrong. If you use the serialize() Jquery function, the good header is not dataType:json
but dataType:x-www-form-urlencoded
. Then, the form is correctly add to the Request object and the form can be handled with $form->handleRequest($form)
.