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,但在使用正常提交按钮提交时工作正常。
我也试图将结果发送到不同的路线,但同样的结局......
我在做什么错?我在圈子里跑......
谢谢您的回答。不幸的是,我仍然得到相同的... $ formpref-> isValid()返回false ... 此外$ formpref-> getErrorsAsString()返回一个空字符串与我的和你的解决方案... – Alberto 2014-11-05 12:01:49
什么错误你会得到表单错误?你有你的csrf令牌生成并通过ajax调用传递? – 2014-11-05 12:03:17
感谢您的解决方案,我终于找到了错误。 我实际上没有发送数据。表单以奇怪的方式生成,id为“formpref”的div为空。我不得不按名称选择表格。自从我看到id =“formfood”后我感到困惑,但没有意识到它是空的。感谢您的时间和帮助。 – Alberto 2014-11-05 12:19:44