【问题标题】:Symfony2: cannot submit form with ajaxSymfony2:无法使用 ajax 提交表单
【发布时间】:2015-01-01 13:49:51
【问题描述】:

我正在尝试通过 ajax 调用提交使用 symfony2 创建的表单。 我知道那里有很多教程,但我认为我做的一切都是正确的,但仍然无法让它发挥作用。

这是我在控制器中的代码:

/**
 * @Route("/preferences", name="_mybundle_preferences")
 * @Template()
 */
public function preferencesAction(Request $request)
{

    $em = $this->getDoctrine()->getManager();

    $allprefs = $em->getRepository('MyBundle:MyPrefs')
                ->findAllPrefs();

    // Creating the form
    $defaultData = array();
    $formpref = $this->container
            ->get('form.factory')
            ->createNamedBuilder(
                'formpref', 
                'form', 
                $defaultData, 
                array('validation_groups' => array())
            );

    // Input the search field 
    // (will be connected to a jQuery function to filter results)
    $formpref->add('search', 'search', array( 'mapped' => false) );

    // Populate the list of choice fields where the user can select its 
    // preferences
    foreach ( $allprefs as $mypref)
    {
            $fieldname = $mypref->getId();
            $formpref->add($fieldname, 'choice', array(
                'choices' => array( 
                    '3' => 'Very', 
                    '2' => 'Quite', 
                    '1' => 'Poor', 
                    '0' => 'None'
                    ), 
                'expanded'    => false, 
                'label'       => $mypref->getName(),
                ));
    }

    // Just temporary, I want to remove it through ajax
    $formpref->add('send', 'submit');    

    // Get the form
    $formpref = $formpref->getForm();

    // Handle the request
    $formpref->handleRequest($request);

    if ($formpref->isValid()) {

        // do stuff

        $response = array("success" => true);
        return new Response(json_encode($response));

    }

    $result = array(
      'forms' => $formpref->createView(),
      );

    return $result;

}

在我的树枝上:

<div id="div1" data-path="{{path('_mybundle_preferences')}}">
</div>

    {{ form(forms) }}

还有 jQuery 脚本

$("select").change( function(){

    // I am using an array to check how many output requests I already made
    var myArray = [];

    myArray.push( 1 ); 

    $("#div1").html("Saving...");

    $.ajax({
        type: "POST",
        url: $('#div1').data('path'),
        data: $("#formpref").serialize() ,
        async: true,
        dataType: "json",
        success: function(response) {
            myArray.pop();
            if (myArray.length === 0) { 
                $("#div1").html("All changes saved"); 
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
          console.log('Error : ' + errorThrown);
        },
    });

    return false;
});

通过代码中插入的一些 file_put_contents(此处未显示)我可以 看到 $formpref->isValid() 调用永远不会在表单返回 true 时 使用 ajax 提交,但使用普通提交按钮提交时可以正常工作。

我也尝试将结果发送到不同的路线,但结果相同......

我做错了什么?我在兜圈子……

【问题讨论】:

    标签: jquery ajax forms symfony


    【解决方案1】:

    我认为$("#formpref").serialize() 可能是问题所在。试试这个代码来序列化你的表单:

    var values = {};
    var $form = $("#formpref"); //I assume formpref is id of your form
    $.each($form.serializeArray(), function (i, field) {
        values[field.name] = field.value;
    });
    

    然后使用:

    $.ajax({
        data: values ,
        (...)
    });
    

    【讨论】:

    • 感谢您的回答。不幸的是,我仍然得到相同的结果... $formpref->isValid() 返回 false... 此外 $formpref->getErrorsAsString() 正在返回一个空字符串,其中包含我和您的解决方案...
    • 您会收到哪些表单错误?您是否通过 ajax 调用生成并传递了您的 csrf 令牌?
    • 感谢您的解决方案,我终于找到了错误。我实际上没有发送任何数据。该表单以一种奇怪的方式生成,其中 id="formpref" 的 div 为空。我必须按名称选择表格。看到 id="formfood" 后我很困惑,但没有意识到它是空的。感谢您的时间和帮助。
    • @Alberto:当有多个具有相同 ID 的 DOM 元素时,这可能是问题;)
    猜你喜欢
    • 2014-09-12
    • 2012-05-05
    • 2015-10-16
    • 1970-01-01
    • 2023-04-10
    • 2015-03-27
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多