douturan1807 2018-07-20 21:47
浏览 61
已采纳

处理Ajax请求Symfony

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.

  • 写回答

1条回答 默认 最新

  • doucheng3811 2018-07-21 08:26
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么