1
我在Symfony中有一个需要通过ajax调用提交的表单。我编码的代码,但它并没有保存任何数据在数据库中,但也没有给/显示任何错误。Symfony2通过Ajax保存表单数据
send_dict = {
type: 'POST',
url: $(this).attr('action'),
processData: true,
data: $('#Form').serialize(),
beforeSend: function(request) {alert('before send');},
success: function (data) {alert("success")},
error: function(xhr, textStatus, thrownError) {
alert('Some Thing Went Wrong, Please Refresh and Try Again...');
}
}
$.ajax(send_dict);
public function createAction(Request $request)
{
$user = $this->getUser();
$address = new Addresses();
if($request->isXmlHttpRequest()) {
// Do something...
if ($request->isMethod('POST')) {
$request = $this->get('request');
$permanent_is_present = $request->get('permanent_is_present');
$present_address = $request->get('present_address');
$present_address_country = $request->get('present_address_country');
// Persisting Objects to the Database
if($permanent_is_present==true){
$address->isIsPresent(true);
$address->isIsPermanent(true);
}else{
$address->isIsPresent(true);
}
$address->setUser($user);
$address->setStreet1($present_address);
$address->setCountry($present_address_country);
$address->setState($present_address_state);
$address->setCity($present_address_city);
//exit(\Doctrine\Common\Util\Debug::dump($address));
// Entity Manager To Get Connected with Doctrine
$em = $this->getDoctrine()->getManager();
// Persists the entire objects....
$em->persist($address);
// Flush queries into database
$em->flush();
$output = array();
$response = new Response();
$output[] = array('success' => true);
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}else{
return $this->render('AddressBundle:Addresses:new.html.twig');
}
} else {
return $this->redirect($this->generateUrl('address_new'));
}
}
这两个警报在发送和成功上的ajax函数都显示。但数据不会保存在数据库中?新的symfony,也不知道如何跟踪/调试呢?
更新: 还有一件事我注意到,系统中没有用户登录,他们试图做ajax调用。并且它正在发送到控制器,并且因为未找到用户标识,所以它未保存到数据库中
可能是一个与'$(this).attr('action')有关的范围问题' - 你期望'this'指什么? – Steve
创建表单对象控制器端,然后绑定请求。然后你可以正确验证。 [heres](http://codemonkeys.be/2013/01/ajaxify-your-symfony2-forms-with-jquery/)合理的资源来帮助你。 – DevDonkey
@Steve'action =“{{path('address_create')}}”' –