简体   繁体   中英

Submit JQuery Form $.post() handle display message on success

I have a form I am submitting with $.post() in jquery..

$.post("testpage.php", $("#payment-form").serialize())

The post works fine itself, but when the post is done and successful the page will do other stuff such as display a thank you message and stuff. I just need to where to put to call to display the message.I do not understand where it goes in terms of the success being returned from the post.

You can specify a 3rd argument to .post() that is the "success" callback. It is a function to call when the .post execution is successful.

$.post("testpage.php", $("#payment-form").serialize(), function() { alert('post was successful!')})

Source: http://api.jquery.com/jquery.post/

In short, like this:

$.post("testpage.php", $("#payment-form").serialize(), function () {
    // Start partying here.
}).fail(function() {
    // Handle the bad news here.
})

Alternatively, you can use deferred objects , like as follow:

// Create POST request
var paymentPost = $.post("testpage.php", $("#payment-form").serialize());

// Assigned deferred objects
// "data" refers to the data, preferably in JSON format, returned by testpage.php
paymentPost
.done(function(data) {
    // Success
    // e.g. display thank you message, redirect to a payment successful page...
})
.fail(function(data) {
    // If error
    // e.g. display error message(s)
})
.always(function() {
    // Will always fire as long as POST request is submitted and completed
});

p/s: It is important to note that jqXHR methods like .success() and .error() are deprecated. To prepare for their eventual removal, you should abide to the new nomenclature for deferred objects ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM