How to Ajax POST after a Form Submit

后端 未结 2 1175
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 07:40

I think this is pretty simple but I cannot find anywhere how to do this, as the title says, how do you do an ajax post after a successful submit form post. I tried to search for

2条回答
  •  执念已碎
    2021-01-25 08:20

    What you should do is "take over the submit button" with your jQuery, and then use an ajax call inside.

    For example having this submit button:

    
    

    And having this jQuery submit function with an ajax call, should give you a pretty good idea on what to do.

    $('#your-form-id-here').submit(function (e) {
    
        e.preventDefault();
        var senddata = $(this).serializeArray();
        var sendto = $(this).attr("action");
    
        $.ajax({
            url: sendto,
            type: 'POST',
            data: senddata,
            success: function (data) {
                $('.messages').html(data);
            },
            error: function (error) {
                $('.messages').html(error);
            }
        });
    });
    

    This basically takes your normal form, and send it through your ajax call, to your normal form action, so basically it works just like normal, but you now have the opportunity to do stuff in your form action php file, and also in your ajax success data. For example you could use this to deliver validation messages directly to your user, without refreshing your site. And so on...

提交回复
热议问题