Mick
Mick

Reputation: 31959

Display form via Ajax

Edit

Many questions on SO are about form submission via Ajax (this one is very popular) but not about how to display a form through an ajax call.

My question is about the part in bold: the user asks for a form -> ajaxCall -> displayForm -> user submit the form -> send the form to the controller -> validates form -> send response to the user (errors or not).


The question

The ajax call being a POST, $request->isMethod('POST') always returns true when doing an ajax call. Therefore if a new form is being requested through an ajax call, it will always be validated. I have enclosed the code below, the form is displayed ok, but the following error message is displayed in the form:

The CSRF token is invalid.

The problem is that the form is being validated during the ajax call requestion the form in the controller.

On a side note, submitting the form works well, and validation works well.

Does anyone know how to display a form via Ajax without having the blank new form being validated?

My code so far:

/**
 * Display the message as well as the form to reply to that message
 *
 * @param Request $request
 * @return Response
 */
public function viewMessageAction(Request $request)
{
    //Forbid every request but jQuery's XHR
    if (!$request->isXmlHttpRequest()){
        return new Response('', 200, array('Content-Type' => 'application/json'));
    }

    //Retrieve the message from the request
    $messageId = $request->request->get('messageId');
    $message = $this->getMessageManager->getMessage($messageId);

    //Creates the form to reply to the message
    $form = $this->container->get('reply_form.factory')->create($message);

    if ($request->isMethod('POST')) {
        $form->bind($request);

        if ($form->isValid()) {
            //...
            return $this->redirect($this->generateUrl('task_success'));
        }
    }

    $answer =$this->container->get('templating')->renderResponse('AcmeMessageBundle:Message:message.html.twig', array(
        'form' => $form->createView(),
        'message' => $message
    ));

    $response = new Response();
    $response->headers->set('Content-type', 'application/json; charset=utf-8');
    $response->setContent(json_encode($answer));
    return $response;

}

EDIT: jQuery part:

<script type="text/javascript">
    $(function(){

        var myPath = ;//...

        function getMessage(messageId){
            $.ajax({
                type: "POST",
                url:  myPath,
                data: "messageId="+messageId,
                success: function(returnData){
                    $('#message').html(returnData);
                }
            });
        }

    });
</script>

Upvotes: 3

Views: 2203

Answers (2)

ferdynator
ferdynator

Reputation: 6410

You might also be interessted in the FOSJsRoutingBundle, since it add a lot of comfort working with ajax and Symfony2 routes in general.

Upvotes: 0

Sethunath K M
Sethunath K M

Reputation: 4761

An ajax call doesnt always need to be POST. It could be GET, PUT or DELETE . So when you are making ajax call to get the form make it a GET request.

If you are using jquery here is how you do that

$.ajax({
   url: "http://localhost/proj/url",
   type:'GET'
})

If you are using Using XHR, you can specify the type in the open function

xhr.open( 'GET', URL)

PS: It will be a good idea to use JMS Serializer Service for serialization instead of json_encode

Upvotes: 2

Related Questions