dongzaocheng3214 2017-12-18 21:54
浏览 34
已采纳

使用Ajax提交2个symfony表单

I'm trying to submit 2 symfony forms in one submit using ajax

var data = $('#facebookPostTargetForm').serialize();
data = data.concat("
", $('#facebookPostForm').serialize());
$.ajax({
    url: '{{ path('facebookpostwizard_new') }}',
    type: "POST",
    data: data,
    dataType: 'html',
    success: function(data){
    //console.log(data);
    alert('OK');
    }
    });

almost everything is working properly except the case that in my controller when I use $form->handleRequest($request) i get some trouble getting the last field of first form(mostly _token so $form->isValid() always return false) and first field of second one!!!! I don't put a snippet of my controller here because if I only submit one form everything works perfect, it seems to be related to the data.concat() but I've tried a lot of things and it doesn't work. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongliu6848 2017-12-18 22:19
    关注

    Without knowing your PHP code, I can only guess what the issue is. But I suspect you are not handling the Array that you receive correctly. Or rather, you are trying to build something totally different from what you are actually sending.

    concat() does not concatenate strings but Arrays. If you just want to concatenate the serialized query strings of the forms, you can simply use + operator like this:

    var data = $('#facebookPostTargetForm').serialize() + '&' + $('#facebookPostForm').serialize();
    

    This will make one big query string from both forms and you will have them available as POST variables in the $request object. Note that this will only work if the fields in both forms are named differently. If a field has the same name, form2 will override form1.

    If you use the same field names and want to handle the forms separately, you should post an object instead of a form:

    var data = {
        'form1': $('#facebookPostTargetForm').serializeArray(),
        'form2': $('#facebookPostForm').serializeArray()
    };
    

    This will submit an object ob objects (or a multidimensional associative array in PHP speech). You can then access them in PHP like this:

    $form1 = $request->get('form1');
    $field1 = $form1['field1']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题