Symfony2:无法使用ajax提交表单

时间:2014-11-05 11:24:58

标签: jquery ajax forms symfony

我正在尝试通过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-&gt; isValid()调用在表单时永远不会返回true 使用ajax提交,但在使用普通提交按钮提交时工作正常。

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

我做错了什么?我在圈子里奔跑......

1 个答案:

答案 0 :(得分:0)

我认为$("#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 ,
    (...)
});
相关问题