phpjqueryajaxformssubmission

How to add AJAX Form-Submission Error Alert?


Novice web developer here. I've added a tutorial-based PHP-AJAX-jQuery form, which also features a loading GIF. On testing, I've found that the hidden, div-contained "Submission Success" message below the form would replace the loading GIF if any form submission successfully inserts a new database entry, and in any instance that submission fails to insert a new database entry, the loading GIF would just remain visible and nothing further happens. I'm wondering if there's a relative simple change I can make to the AJAX code so that if a form submission fails to result in a new database entry, then the loading GIF would be hidden and another div-contained alert would display (such as the new div-contained alert wrapped in double asterisks in the code below)? Alternatively, if that option is more complex than I realize, I appreciate any suggestions for integrating an AJAX alert to simply notify the user that the form submission was not received. Thanks!

<form id="contact">
  ...
  <button name="submit" type="submit" id="submitBtn">Submit</button>
  <img src="../../images/loading-dots.gif" id="loader" style="display: none">
</form>
<div id="successMsg" class="style_success">Message sent successfully!</div>
**<div id="errorMsg" class="style_error">An error occurred. Please try contacting us via email instead.</div>**

*Last div-contained message (wrapped by double asterisks) is what I want to display if there is an error on processing the form data.

$("#submitBtn").hide('fast');
$("#loader").show('fast');
$.ajax({
    url:"private/php_scripts/submission.php",
    data:{key:"saveData",name:name,email:email,message:message},
    method:"POST",
    success:function (response) {
        var data = response.split('^');
        if (data[1] == "saved") {
            $("#submitBtn").show('fast');
            $("#loader").hide('fast');
            $("#successMsg").show('fast');
            $("#successMsg").fadeOut(10000);
            $("form#contact").each(function () {
                this.reset();
            });
        }
    }
});

Solution

  • After clarifying my question for @StackSlave's comment and thinking further on what I'm trying to accomplish, I realized that all I needed to do was copy the if statement under success:function and pasted it in as an else if statement for data!==saved, and then change #successMsg to #errorMsg for my new div message. Thanks.