Symfony2 Form with CSRF passed through JQuery AJAX

前端 未结 1 1538
暗喜
暗喜 2021-02-01 23:12

I am developing a comments box that will save the comment through a JQuery AJAX call.

JQuery

Here\'s the JQuery code for that (this works seamle

1条回答
  •  -上瘾入骨i
    2021-02-01 23:33

    Try with the adequate JQuery function: submit() ^^ In my solution I suppose that your form has the id "comment_form". Works on all my sf2 projects:

    $('#comment_form').submit(function(e) {
    
        var url = $(this).attr("action");
    
        $.ajax({
            type: "POST",
            url: url, // Or your url generator like Routing.generate('discussion_create')
            data: $(this).serialize(),
            dataType: "html",
            success: function(msg){
    
                alert("Success!");
    
            }
        });
    
        return false;
    
    });
    

    The CSRF Field would normally be sent !

    And don't forget to add the twig tag {{ form_rest(form) }} in your form template, that will generate all hidden field like CSRF.

    0 讨论(0)
提交回复
热议问题