Set a JavaScript Callback on Form Submission

Sometimes you might want to trigger an action after the form is submitted. The function setForm() we've been using to reset our forms when using other scripts allows you to do just that.

For instance, say your form is divided into tabs and you want to trigger the first tab to show the success message after the form is successfully submitted.

The callback function will send you back 3 parameters:

  • the first parameter is a boolean that indicates if the operation was successful or not
  • the second parameter is a string that indicates which operation it was. It can have 1 of 4 values:
    • an empty string (when the first parameter is FALSE) meaning there was an error
    • "message" (the first parameter is TRUE) when the form was sent successfully and we're showing a success message
    • "redirect" (the first parameter is TRUE) when the form was sent successfully and we're redirecting to a success page
    • "confirmation" (the first parameter is TRUE) when the form is waiting for a confirmation from the user before sending
  • the third parameter is the form itself as a DOM object
So here's an example showing how to use all this. You will notice, in this example, I only use one form with a known bID but you can also do as we did above and grab all the forms in a loop.

if (typeof ajaxForms_express_form !== "undefined") {
    var knownBID = 123;
    var obj = ajaxForms_express_form[knownBID];
    var callback = function(successactionform) {
        var resultMsg = success ? "success" : "failure";
        console.log("the operation was a " + resultMsg);
        switch (action) {
            case "message":
                console.log("showing you a success message");
                break;
            case "redirect":
                console.log("redirecting soon");
                break;
            case "confirmation":
                console.log("waiting for confirmation");
                break;
            default:
                break;
        }
    };
    if (obj) {
        obj.setForm(false, callback);
    }
}

You will notice that I set the first parameter in the setForm() function to FALSE since I am not sending a DOM object myself.