简体   繁体   中英

Can we process a form with Symfony2 without redirect to another url at the end?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM