Reputation: 859
I have problem with processing the data on a form in two tables with Ajax for not updating screen. Sumfony2 redirects to process the data to a url in the end, as you can see in the following code:
public function createAction(Request $request)
{
$entity = new Users();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('users_new'));
}
return $this->render('BackendBundle:Userss:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
ajax call:
$('.form_student').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
success: function(response) {
alert(response.result);
},
error: function (xhr, desc, err){
alert("error");
}
})
return false;
});
Is there any way that does not forward it to any URL and can use Ajax to load anything in that window?
Upvotes: 1
Views: 2322
Reputation: 39380
You can check on the $request if is an ajax call with the isXmlHttpRequest
method.
So you can do something like:
use Symfony\Component\HttpFoundation\JsonResponse;
....
if ($form->isValid()) {
// do something
if ($request->isXmlHttpRequest()) {
// generate a response for tour client, as example:
return new JsonResponse(array("result" => 1);
}
return $this->redirect($this->generateUrl('users_new'));
}
Hope this help
Upvotes: 1
Reputation: 283
replace
return $this->redirect($this->generateUrl('users_new'));
by
return new JsonResponse($this->generateUrl('users_new'));
this will return the url instead of redirecting to it, you can then use javascript to load it.
Upvotes: 1