How to submit form ajax in symfony2?
Asked Answered
E

2

13

I am about to submit my form Using Ajax,i have successfully submit my form using POST but don't know how to use Ajax with Symfony

builform

    $builder->add('name', 'text', array('constraints' => array(new NotBlank()), 'attr' => array('placeholder' => 'Name')))
        ->add('gender', 'choice', array('empty_value' => 'Select Gender', 'constraints' => array(new NotBlank()), 'choices' => \AppBundle\Entity\Records::$gender_list, "required" => true))
        ->add('dateOfBirth', 'birthday', array('label' => 'Date Of Birth','required'=>true))
        ->add('image_path', 'file', array('label' => ' ','required'=>false, 'data_class' => null, 'constraints'=>array(new Assert\File(                                             array('mimeTypes'=>$mime_types, 'maxSize'=>'2048k' )))))
        ->add('country_of_birth', 'entity', array('empty_value' => 'Country of Birth',
            'class' => 'AppBundle\Entity\Location',
            'property' => 'country',
            'label' => 'Country of Birth'
        ))
        ->add('religion', 'entity', array('empty_value' => 'Select Religion',
            'class' => 'AppBundle\Entity\Religion',
            'property' => 'name',
            'label' => 'Religion'
        ));

Action

        $success = false;
        $record_rep = new \AppBundle\Entity\Records();
        $form = $this->createForm(new \AppBundle\Form\AddPersonType(), $record_rep);

        if ($this->getRequest()->getMethod() == 'POST') {
            $form->submit($request);
            if ($form->isValid()) {
                $data = $form->getData();
                $file = $data->getImagePath();
                $image = $file->getClientOriginalName();

                $new_image_name = $this->hanldeUpload($image, $file);
                $this->savetoDB($data, $record_rep, $new_image_name);
                $success = true;
            }
        }
        return $this->render('AppBundle:Homepage:add_person_form.html.twig', array('form' => $form->createView(), 'success'=>$success ));
    }
Endearment answered 9/4, 2015 at 14:41 Comment(0)
U
23

With jQuery, use serialize() the form and post it to your route.

$('#form').submit(function(e) {

    e.preventDefault();
    var url = "{{ path('YOUR_PATH') }}";
    var formSerialize = $(this).serialize();
    
    $.post(url, formSerialize, function(response) {
        //your callback here
        alert(response);
    }, 'JSON');
});

In your action

if ($form->isSubmitted() && $form->isValid()) {

....

  // or return new JsonResponse($anyData);
  return new Response(json_encode(['status'=>'success']));
}

it must be ok like this. but you can add some parameters like the format, methods etc... in your routing.

Univalve answered 9/4, 2015 at 15:57 Comment(4)
my action already render html so when i tried your solution it always render the success value = false,so it must do i need to handle in my view in addition that i have image so does this block ajax to be performed ?Endearment
Looks like the last line of the top code block should be }); instead of } -HTHVogue
return new Response(json_encode(array('status'=>'success')); is missing a final closing parenthesis. Should be return new Response(json_encode(array('status'=>'success'))); -HTHVogue
Doesn't work with symfony 4 anymore. It says "Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid()."Ambivert
E
3

For the Ajax:

 $("#person").submit(function(e){


    var formURL = "{{ path('form') }}";
    var formData = new FormData(this);
    $.ajax({
        url: formURL,
        type: 'POST',
        data:  formData,
        mimeType:"multipart/form-data",
        contentType: false,
        cache: false,
        processData:false,
        success: function(data, textStatus, jqXHR)
        {

        },
        error: function(jqXHR, textStatus, errorThrown)
        {
        }
    });
    e.preventDefault(); //Prevent Default action.
    e.unbind();
});
$("#person").submit();

And for Action

if ($request->isXmlHttpRequest()) {

....

    return new Response(json_encode(array('status'=>'success')));
}
Endearment answered 9/4, 2015 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.