How to Ajax POST after a Form Submit

后端 未结 2 1176
被撕碎了的回忆
被撕碎了的回忆 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:

    <input type="submit" value="Submit" onsubmit="$('#your-form-id-here').submit()">
    

    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...

    0 讨论(0)
  • 2021-01-25 08:36

    i'm not sure what you are trying to do, what the point of doing ajax request after submitting the form the page will reload anyway.

    however if need need do the ajax request after the submitting the form you just need an ajax call. but that that will work on every time when page load.

    what i think you need to do make two ajax request the first one is for the submitting the form and if the call is successful then call the second request.

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