Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

javascript - Prevent page reload and redirect on form submit ajax/jquery

I have looked through all the similar posts out there but nothing seems to help. This is what I have

HTML:

<section>
  <form id="contact-form" action="" method="post">
    <fieldset>
      <input id="name" name="name" placeholder="Name" type="text" />
      <input id="email" name="email" placeholder="Email" type="text" />
      <textarea id="comments" name="comments" placeholder="Message"></textarea>
      <div class="12u">
        <a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a>
        <a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a>
      </div>
      <ul id="response"></ul>
    </fieldset>
  </form>
</section>

JavaScript/jQuery:

function sendForm() {
  var name = $('input#name').val();
  var email = $('input#email').val();
  var comments = $('textarea#comments').val();
  var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
  $.ajax({
    type: 'post',
    url: 'js/sendEmail.php',
    data: formData,
    success: function(results) {
      $('ul#response').html(results);
    }
  }); // end ajax
}

What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things. I would really appreciate your help on this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Modify the function like this:

function sendForm(e){
  e.preventDefault();
}

And as comment mentions, pass the event:

onclick = sendForm(event);

Update 2:

$('#form-button-submit').on('click', function(e){
   e.preventDefault();

   var name = $('input#name').val(),
       email = $('input#email').val(),
       comments = $('textarea#comments').val(),
       formData = 'name=' + name + '&email=' + email + '&comments=' + comments;

    $.ajax({
      type: 'post',
      url: 'js/sendEmail.php',
      data: formData,
      success: function(results) {
        $('ul#response').html(results);
      }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...