How to submit form ajax in symfony2?

前端 未结 2 2138
北海茫月
北海茫月 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-13 19:24

    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')));
    }
    
    0 讨论(0)
提交回复
热议问题