简体   繁体   中英

success message not showing after jQuery form submission

I have used following jQuery + AJAX for sending a form. It is posting the data to PHP but after success, is not showing the success message.

I would also like to empty the input fields after submission.

function sendContact() {
  event.preventDefault();
  var valid;

  valid = validateContact();
  if (valid) {
    jQuery.ajax({
      url: "  ",

      data: 'userName=' + $("#userName").val() + '&userEmail=' + $("#userEmail").val() + '&subject=' + $("#subject").val() + '&content=' + $(content).val(),
      type: "POST",
      success: function(data) {
        $("#mail-status").html(data);
        $('#mail-status').show();
        $("#frmContact").hide();

        // Clear the form.
        $('#userName').val('');
        $('#userEmail').val('');
        $('#content').val('');
      },
      error: function() {}
    });
  }
}

function validateContact() {
  var valid = true;
  $(".InputBox").css('background-color', '');
  $(".info").html('');

  if (!$("#userName").val()) {
    $("#userName-info").html("(required)");
    $("#userName").css('background-color', '#FFFFDF');
    valid = false;
  }
  if (!$("#userEmail").val()) {
    $("#userEmail-info").html("(required)");
    $("#userEmail").css('background-color', '#FFFFDF');
    valid = false;
  }
  if (!$("#userEmail").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
    $("#userEmail-info").html("(invalid)");
    $("#userEmail").css('background-color', '#FFFFDF');
    valid = false;
  }
  if (!$("#content").val()) {
    $("#content-info").html("(required)");
    $("#content").css('background-color', '#FFFFDF');
    valid = false;
  }
  return valid;
}

HTML:

<div id="frmContact">
  <div id="mail-status" style="display: none;">
    Thanks! Our Admin 'll contact shortly.</div>

  <div>
    <label style="padding-top:20px;">Name</label><span id="userName-info" class="info"></span>
    <br/>
    <input type="text" name="userName" id="userName" class="InputBox">
  </div>
  <div>
    <label>Email</label><span id="userEmail-info" class="info"></span>
    <br/>
    <input type="text" name="userEmail" id="userEmail" class="InputBox">
  </div>

  <div>
    <label>Content</label><span id="content-info" class="info"></span>
    <br/>
    <textarea name="content" id="content" class="InputBox" cols="25" rows="6"></textarea>
  </div>
  <div>
    <button name="submit" class="btnAction" onClick="sendContact();">Send</button>
  </div>
</div>

See this fiddle.

There's a number of recommendations for changes I'd make along with some observations.

First of all, if your form is a form , then use the form element with your #frmContact id. It will be useful for several reasons:

<form id="frmContact" action="/echo/html/" method="POST">...</form>
  1. We can now use the action and method attributes to govern its behaviour on submit. You can update the action to be the URL it should go to and the method - in this case is POST.
  2. Since it is a form, we can now trigger the reset event on it after successful submission, which handles your requirement of emptying the fields.
  3. We can use .serialize() to collect all the form input data, so you don't need to go through your inputs manually selecting what you need and creating a query string.

JS:

$("#frmContact").on("submit", function() {
  event.preventDefault();

  var form = this;

  jQuery.ajax({
    type: form.method,
    url: form.action,
    data: $(form).serialize(),
    success: function(data) {
      $("#mail-status")
        .html(data)
        .show();

      $(form)
        .hide()
        .trigger("reset");
    },
    error: function(xhr, status, error) {
      console.log(error);
    },
    complete: function(xhr, status) {
      console.log(xhr, status);
    }
  });
});

We don't necessarily need any validation function anymore. Just use the HTML5 attributes of required and type=email to validate the email address.

If you really need backward compatibility, by all means change this the way you want, but for a minimal reproducible version of your problem, it's far easier to disregard this in your question.

If you are still having problems, then please provide your PHP and update your question with any feedback from the console in your browser's developer tools console, and also provide your browser name and version.

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