提交表单按钮卡在ajax后

时间:2014-10-07 20:27:12

标签: javascript jquery ajax forms

您好我有一个使用Ajax在Rails 4中发帖的表单.javascript运行一些验证,一旦帖子成功就应该返回一条警告消息。目前,提交按钮保持按下状态,虽然表单上没有消息得到警告。我不知道我做错了什么,只是希望表单提醒消息然后自行重置。

$('#submit1').click(function(e){
  e.preventDefault();
  var name = $('input#name').val();

  if (name == "") {
    alert("please enter a name!");
    $('input#name').focus();
    return false;
  }
  var email = $('input#email').val();

  if (email == ""){
    alert("please enter your email");
    $('input#email').focus();
    return false;
  }
  var content = $('textarea#text').val();

  if (content == ""){
    alert("please enter a comment");
    $('textarea#text').focus();
    return false;

  }

  var dataString = 'name=' + name + '&email=' + email + '&content=' + content;


  $.ajax({
    type: "POST",
    url: "emailer",
    data: dataString,
    dataType: 'json',
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
    success: function(){
      alert("mappy jappy");
      $('input#name').reset();
      $('input#email').reset();
      $('textarea#text').reset();
    }
  });
  return false;
});

2 个答案:

答案 0 :(得分:1)

您正在阻止错误的事件。您需要表单的'onsubmit'事件而不是提交按钮的'onclick'事件。

$('#myform').on('submit', function(event){
  event.preventDefault();
  /* your code here */
});

欲了解更多信息,请阅读: How to prevent form from being submitted?

答案 1 :(得分:0)

首先,重置功能不适用于文本框..它将为表单运行。所以纠正后的代码就是......

<script>
$(function(){
$('#submit1').click(function(e){
  e.preventDefault();
  var name = $('input#name').val();

  if (name == "") {
    alert("please enter a name!");
    $('input#name').focus();
    return false;
  }
  var email = $('input#email').val();

  if (email == ""){
    alert("please enter your email");
    $('input#email').focus();
    return false;
  }
  var content = $('textarea#text').val();

  if (content == ""){
    alert("please enter a comment");
    $('textarea#text').focus();
    return false;

  }

  var dataString = 'name=' + name + '&email=' + email + '&content=' + content;


  $.ajax({
    type: "POST",
    url: "user_availability.php",
    data: dataString,
    dataType: 'json',
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
    success: function(){
      alert("mappy jappy");
      $('#contact-form')[0].reset();
    }
  });
  return false;
});
});
</script>

和html部分如下 -

<form id="contact-form" method="post" enctype="multipart/form-data">
<input type="text" id="email" name="email" />
<input type="text" id="name" name="name" />
<textarea name="text" id="text"></textarea>
<input type="submit" value="submit" id="submit1" />
</form>

请检查并告诉我......