nowiko
nowiko

Reputation: 2557

submit form by ajax in Symfony2

I have action what first need to render form by ajax and then need to update existing values. I already get rendered form with proper values, but when I click to submit form by ajax I cant prevent form submission, I have this script:

 $('#edit-comment').click(function (e) {
    e.preventDefault();
    console.log(1);
});

But submitting with still work ! What I am doing wrong. And I dont know how I need to handle submitted form in the edit action. Here is existing part of it:

 /**
 * @Route("/edit/comment", name="chat_edit", options={"expose"=true})
 */
public function editAction(Request $request)
{
    $comment_id = json_decode($request->getContent(), true)['commentId'];
    $comment = $this->get('comment.repository')->find($comment_id);
    $form = $this->createForm(new CommentType(), $comment);

    return $this->render("ChatCommentBundle:Comment:form.html.twig",
        array('form' => $form->createView())
    );
}

Link to gist with form type

Upvotes: 2

Views: 1087

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Update:

The original answer (below) still applies, but given that the form is actually loaded using AJAX, you can't bind the event listeners in the $(document).ready callback. The best option for you is to use event delegation. This is done by attaching an event listener to a DOM element that does exist from the start, but have that listener pick up on events for elements that might be added later on. For example: the body element will always exist, so you can listen for a form submission there, whether or not that form exists doesn't matter:

$('body').on('submit', '#form-id', function(e)
{
    console.log('#form-id was submitted, do AJAX => submission stopped');
    return false;
    //or
    e.preventDefault();
    e.stopPropagation();
});

The why and how this works is very well explained here. It boils down to the fact that all events pass through all of the parent DOM elements of the target node, so you can attach listeners anywhere in the DOM, and handle the events before they reach their target.
I think this old answer of mine might explain a thing or 2, too. It doesn't use jQ, but it contains a simplified version of the code that jQ uses internally for delegation.


You're preventing the default effects of the click event on $('#edit-comment'), but that event still propagates through to the form. You might want to add e.stopPropagation(), too. Or simply return false; from the callback (which prevents the default and stops propagation).

However, a better way to prevent the form from being submitted is to use the submit event, and stop the submission there:

$('#form-id').on('submit', function(e)
{
    console.log('Do ajax call here');
    return false;
    //or
    e.preventDefault();
    e.stopPropagation();
});

Upvotes: 3

Related Questions