Symfony2 - Sending other data along with form data via Ajax causes IsValid() return false

barigain

Junior Member
Joined
Aug 23, 2012
Messages
100
Reaction score
12
I'm trying to send other data along with a submitted form to a controller inside Symfony2.
When I try this like:

PHP:
$("#submit_btn").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: post_url,
            data: form.serialize()
        });
    });
I see i got a successful POST request followed by a redirect as intended inside the controller action, If IsValid() returned true.

But when I try to send other data with the form like:
PHP:
$("#submit_btn").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: post_url,
            data: { form: form.serialize(), otherdata: "test" }
        });
    });
I do not get the redirection 302 response. instead I get only one 200 response when means IsValid() method returned false.
My question here how to not only send form, but also other data with it ?

Here's my controller action:

PHP:
public function postOverviewAction(Request $request, $id)
    {
        $overview = $this->get("doctrine_mongodb")->getRepository("GbrBEBundle:Overview")->findOneById($id);
        $overview_photos = $this->get("doctrine_mongodb")->getRepository("GbrBEBundle:OverviewPhoto")->findAll();
        $form = $this->createForm(new OverviewType(), $overview);        $form->handleRequest($request);

        $height = $form->get("coordinate_height")->getData();
        $width = $form->get("coordinate_width")->getData();
        $x = $form->get("coordinate_x")->getData();
        $y = $form->get("coordinate_y")->getData();
        if($form->isValid())
        {
            $overview->setCropCoordinates(array('height' => $height, 'width' => $width, 'x' => $x, 'y' => $y));
            $dm = $this->get("doctrine_mongodb")->getManager();
            $dm->persist($overview);
            $dm->flush();
            return $this->redirect($this->generateUrl("gbr_be_get_overview"));
        }
        return $this->render("GbrBEBundle:Default:overview.html.twig", array(
            "form" => $form->createView(),
            "overview" => $overview,
            "overview_photos" => $overview_photos,
        ));
    }

Thank you!
 
JQuery serialize() returns a query string. Try this code:
PHP:
$("#submit_btn").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: post_url,
            data: form.serialize() + "&otherdata=test"
        });
    });
 
Back
Top