简体   繁体   English

jQuery表单提交后未显示成功消息

[英]success message not showing after jQuery form submission

I have used following jQuery + AJAX for sending a form. 我已经使用以下jQuery + AJAX发送表单。 It is posting the data to PHP but after success, is not showing the success message. 它正在将数据发布到PHP,但成功后未显示成功消息。

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: 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. 首先,如果您的表单是form ,则将form元素与#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. 现在,我们可以使用actionmethod属性来控制其在提交时的行为。 You can update the action to be the URL it should go to and the method - in this case is POST. 您可以将操作更新为应转到的URL和方法-在这种情况下为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. 由于它是一种表单,因此我们现在可以在成功提交后在其上触发reset事件,这可以满足您清空字段的要求。
  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. 我们可以使用.serialize()来收集所有表单输入数据,因此您无需手动检查输入内容就可以选择所需的内容并创建查询字符串。

JS: 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. 只需使用requiredtype=email的HTML5属性来验证电子邮件地址。

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. 如果仍然有问题,请提供您的PHP并使用浏览器开发人员工具控制台中控制台的任何反馈来更新您的问题,并提供您的浏览器名称和版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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