How to submit form ajax in symfony2?

前端 未结 2 2149
北海茫月
北海茫月 2021-02-13 19:08

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

2条回答
  •  Happy的楠姐
    2021-02-13 19:24

    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.

提交回复
热议问题