2014-11-05 55 views
0

我想通過ajax調用提交一個用symfony2創建的表單。 我知道那裏有很多教程,但我認爲我做的一切都正確,但仍然無法成功實現。Symfony2:無法用ajax提交表格

這是我在控制器代碼:

/** 
* @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()調用neve r在表單爲 的情況下返回true,但在使用正常提交按鈕提交時工作正常。

我也試圖將結果發送到不同的路線,但同樣的結局......

我在做什麼錯?我在圈子裏跑......

回答

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 , 
    (...) 
}); 
+0

謝謝您的回答。不幸的是,我仍然得到相同的... $ formpref-> isValid()返回false ... 此外$ formpref-> getErrorsAsString()返回一個空字符串與我的和你的解決方案... – Alberto 2014-11-05 12:01:49

+1

什麼錯誤你會得到表單錯誤?你有你的csrf令牌生成並通過ajax調用傳遞? – 2014-11-05 12:03:17

+0

感謝您的解決方案,我終於找到了錯誤。 我實際上沒有發送數據。表單以奇怪的方式生成,id爲「formpref」的div爲空。我不得不按名稱選擇表格。自從我看到id =「formfood」後我感到困惑,但沒有意識到它是空的。感謝您的時間和幫助。 – Alberto 2014-11-05 12:19:44