LargeTuna
LargeTuna

Reputation: 2824

Symfony2 Ajax jQuery

I am having a bit of an issue trying to get Symfony and ajax to play nicely with each other. I am newbie to this whole world of Symfony and ajax so go easy on me. I am sure my code is a nightmare, but I am learning :)

I am able to create a form and post my data to Symfony without Ajax (posting through a URL) But, when I try and do it via ajax (the exact same form) I get a json response of 400. I know it has to do with Symfony not being able to understand the post data that is coming into it. In my controller action, it processes fine until it gets to the section "if($form->isValid())", this is where Symfony does not like my form.

Here is my jQuery ajax to send the post data via the form:

 $(document).ready(function() {
        $("#myForm").submit(function(){

            // My form
            var $form = $(this).closest("#myForm");

            // If valid
            if($form){

                // The url where the form is being posted via ajax
                var url = $("#myForm").attr("action");

                // Post the data
                $.post(url,{
                    type: "POST",
                    data: $form.serialize(), // serializing the data being sent 
                    cache: false
                },function(data){

                    // If valid
                    if(data.responseCode == 200 ){
                        alert(data.responseCode);
                    }
                    else if(data.responseCode==400){
                        alert(data.responseCode);
                    }else{
                        alert("bad response all together...");
                    }
                }); 
            }
            return false;
        });
    });

Here is my form that was created via the Symfony form builder:

 <form novalidate class="form-horizontal" id="myForm" action="/symfonydev/web/app_dev.php/warehouse/ajax/insert/" method="POST" >
 <input type="text" id="warehouse_name" name="warehouse[name]" required="required" placeholder="Location Name" class="input-block-level" value="" />
 <input type="text" id="warehouse_address" name="warehouse[address]" required="required" placeholder="Address" class="input-block-level" value="" />
 <input type="text" id="warehouse_city" name="warehouse[city]" required="required" placeholder="City" class="input-block-level" value="" />
 <input type="text" id="warehouse_state" name="warehouse[state]" required="required" placeholder="State" class="input-block-level" value="" />
 <input type="text" id="warehouse_zip" name="warehouse[zip]" required="required" placeholder="Zip" class="input-block-level" value="" />
 <input type="text" id="warehouse_email" name="warehouse[email]" required="required" placeholder="Email Address" class="input-block-level" value="" />
 <input type="text" id="warehouse_phone" name="warehouse[phone]" required="required" placeholder="Phone" class="input-block-level" value="" />
 <input type="text" id="warehouse_fax" name="warehouse[fax]" required="required" placeholder="fax" class="input-block-level" value="" />
 <input type="hidden" id="warehouse__token" name="warehouse[_token]" value="5352017c711a3a9d87ca9158334b32ab9f1dd3af" />
 <input type="submit" value="Send" />
 </form>

Perhaps because the serialized string of form variables is url encoded, is Symfony not able to parse these out to persist them to the db? When ajax posts the data via the serialized string, the field names are url encoded like this.

 warehouse%5Bname%5D=Test&warehouse%5Baddress%5D=Test&warehouse%5Bcity%5D=Test&warehouse%5Bstate%5D=Test&warehouse%5Bzip%5D=Test&warehouse%5Bemail%5D=Test&warehouse%5Bphone%5D=Test&warehouse%5Bfax%5D=Test&warehouse%5B_token%5D=5352017c711a3a9d87ca9158334b32ab9f1dd3af

This is my controller action:

 public function ajaxinsertAction(Request $request)
{

    // Get user's account
    $account = $this->getUser()->getAccount();

    // Warehouse form
    $warehouse = new Warehouse();
    $form = $this->createForm(new WarehouseType(), $warehouse);

    if ($request->isMethod('POST')) {

        // Get the Account of this user and set it on the warehouse being created.
        $account = $this->getUser()->getAccount();
        $warehouse->setAccount($account);
        $form->bind($request);

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($warehouse);
            $em->flush();

            $return = array("responseCode"=>200, "response"=>"Valid");
            $return = json_encode($return); // json encode the array
            return new Response($return,200,array('Content-Type'=>'application/json'));
            die;

        }else{

            $return = array("responseCode"=>400, "response"=>"Invalid");
            $return = json_encode($return); // json encode the array
            return new Response($return,400,array('Content-Type'=>'application/json'));
            die;
        }
    }
}

Thanks for your help!

Any one have any good tutorials on Symfony and Ajax? I want to learn more about this framework, just seems to be such sparse info besides the docs at Symfony (which are pretty good, though they have little documentation on ajax).

Cheers!

Upvotes: 2

Views: 7978

Answers (2)

Lukas Lukac
Lukas Lukac

Reputation: 8346

For people who search answer for similiar problem after long day and i was distructed..

I was in the very similiar situation. The problem is that you are submiting empty data... you submit form... and then you pull to DOM.

var $form = $(this).closest("#myForm");

It should be only

var form=$(this); 

$.post(url, form.serialize(), function(data) {

});  

Upvotes: 3

Youssef
Youssef

Reputation: 1043

Have you tried passing values manually?

 ...
               $.post(url,{
                    type: "POST",
                    "warehouse[city]": $('#warehouse_city').val(),
                    "warehouse[state]" : $('#warehouse_state').val(),
                    ...
                    cache: false
                }
                ....

Upvotes: 1

Related Questions