使用表单ID提交AJAX表单

时间:2018-03-04 09:41:00

标签: jquery ajax

我在一个页面上有多个AJAX表单,但他们不会提交。表单在Wordpress循环中,每个表单都有一个唯一的ID。我已经定义了表单ID变量,因此我可以触发当前的表单ID进行提交。

JAVASCRIPT

<script type="text/javascript">
  jQuery(document).ready(function ($) {

      var formID = $('form').attr('id')
      var is_sending = false,
    failure_message = 'Whoops, looks like there was a problem. Please try again later.';

    formID.submit(function (e) {
      if (is_sending || !validateInputs()) {
    return false; // Don't let someone submit the form while it is in-progress...
      }
      e.preventDefault(); // Prevent the default form submit
      $this = $(this); // Cache this
      $.ajax({
    url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
    type: 'post',
    dataType: 'JSON', // Set this so we don't need to decode the response...
    data: $this.serialize(), // One-liner form data prep...
    beforeSend: function () {
      is_sending = true;
      // You could do an animation here...
    },
    error: handleFormError,
    success: function (data) {
      if (data.status === 'success') {
        // Here, you could trigger a success message
      } else {
        handleFormError(); // If we don't get the expected response, it's an error...
      }
    }
      });
    });

    function handleFormError () {
      is_sending = false; // Reset the is_sending var so they can try again...
      alert(failure_message);
    }

    function validateInputs () {
      var $name = $('#contact-form > input[name="name"]').val(),
      $email = $('#contact-form > input[name="email"]').val(),
      $message = $('#contact-form > textarea').val();
      if (!$name || !$email || !$message) {
    alert('Before sending, please make sure to provide your name, email, and message.');
    return false;
      }
      return true;
    }
  });
</script>

FORM

<form id="contact-form-<?php echo $pid; ?>">
  <input type="hidden" name="action" value="contact_send" />
  <input type="text" name="name" placeholder="Your name..." />
  <input type="email" name="email" placeholder="Your email..." />
  <textarea name="message" placeholder="Your message..."></textarea>
  <input class="button expanded" type="submit" value="Send Message" />
</form>

2 个答案:

答案 0 :(得分:0)

您可以为每个AJAX表单提供一个单独的类,只是为了识别它并使用data- *属性获取其ID。如:

<script type="text/javascript">
jQuery.on('submit', '.ajax-form', function(e){
e.preventDefault();
var formID = $(this).data('pid');
...
//call $.ajax();
...
}
</script>

HTML格式为:

<form class='ajax-form' data-pid='<?php echo $pid; ?>'>
...
...
</form>

答案 1 :(得分:0)

或只是一个函数:

function submitForm(id){
   // Your AJAX
}
然后表格应该是这样的:

  <form class='ajax-form' id='<?php echo $pid; ?>' onSubmit='submitForm("
<?php echo $pid; ?>")'>
 <!-- inputs-->
</form>