阻止页面重新加载和重定向表单提交ajax / jquery

时间:2022-11-23 19:53:39

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.

我无法做的是在按下#form-b​​utton-submit时阻止页面刷新。我试过回复假;我尝试了preventDefault()和每个组合,包括return false;在onClick里面。我也尝试使用input type =“button”和type =“submit”代替相同的结果。我无法解决这个问题,而且它正在变得疯狂。如果可能的话,我宁愿使用超链接,因为一些设计的东西。我非常感谢你对此的帮助。

7 个解决方案

#1


18  

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);
      }
    });
});

#2


2  

Have you tried using

你尝试过使用过吗?

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

#3


2  

function sendForm(){
    // all your code
    return false;
}

#4


2  

I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-

我也有点想找到解决这个问题的方法,到目前为止,我找到的最佳工作方法是 -

Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-

尝试使用XHR向任何网址发送请求,而不是$ .ajax()...我知道这听起来有点奇怪,但试试看!例-

<form method="POST" enctype="multipart/form-data" id="test-form">

var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();

var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);

var formData = new FormData(document.getElementById('test-form'));
request.send(formData);


This would send your data successfully ...without page reload.

这将成功发送您的数据...无需重新加载页面。

#5


0  

Simple and Complete working code

简单而完整的工作代码

<script>
    $(document).ready(function() {
        $("#contact-form").submit(function() {
            $("#loading").show().fadeIn('slow');
                $("#response").hide().fadeOut('slow');
                 var frm = $('#contact-form');
                 $.ajax({
                     type: frm.attr('method'),
                     url: 'url.php',
                     data: frm.serialize(),
                     success: function (data) {
                         $('#response').html(data);
                         $("#loading").hide().fadeOut('slow');
                         $("#response").slideDown();
               }, error: function(jqXHR, textStatus, errorThrown){
              console.log(" The following error occured: "+ textStatus, errorThrown );
            } });
           return false;
        });
    });
</script>

#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form

#loading可以是一个图像或在表单处理时要显示的内容,使用代码只需创建一个带有ID联系表单的表单

#6


0  

Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:

避免提交表单的另一种方法是将按钮放在表单之外。我有现有的代码正在工作,并根据工作代码创建了一个新页面,并编写了这样的html:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
    <button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>

This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.

该形式导致上述不期望的重定向。将html更改为下面显示的内容可解决问题。

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

#7


0  

I expect anyone to understand my idea very well as it's a very simple idea.

我希望任何人都能很好地理解我的想法,因为这是一个非常简单的想法。

  1. give your required form itself an id or you can get it by any other way you prefer.

    将您所需的表格本身作为身份证明,或者您可以通过您喜欢的任何其他方式获得。

  2. in the form input "submit" call an onclick method from your javascript file.

    在表单输入“提交”中从您的javascript文件调用onclick方法。

  3. in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
    To clarify that see this:

    在这个方法中,一个变量引用你的from id和addEventListener,并在“提交”上创建一个preventDefault方法而不是“click”。澄清一下,看到这个:

    // element refers to the form DOM after you got it in a variable called element for example:
    element.addEventListener('submit', (e) => {
       e.preventDefault();
       // rest of your code goes here
    });  
    

    The idea in brief is to deal with the form by submit event after dealing with submit button by click event.

    简单的想法是在点击事件处理提交按钮后通过提交事件来处理表单。

Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.

无论你在这个方法中需要什么,它现在都可以正常工作而不需要刷新:)只要确保以正确的方式处理ajax就可以了。

Of course it will work only with forms.

当然它只适用于表格。

#1


18  

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);
      }
    });
});

#2


2  

Have you tried using

你尝试过使用过吗?

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

#3


2  

function sendForm(){
    // all your code
    return false;
}

#4


2  

I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-

我也有点想找到解决这个问题的方法,到目前为止,我找到的最佳工作方法是 -

Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-

尝试使用XHR向任何网址发送请求,而不是$ .ajax()...我知道这听起来有点奇怪,但试试看!例-

<form method="POST" enctype="multipart/form-data" id="test-form">

var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();

var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);

var formData = new FormData(document.getElementById('test-form'));
request.send(formData);


This would send your data successfully ...without page reload.

这将成功发送您的数据...无需重新加载页面。

#5


0  

Simple and Complete working code

简单而完整的工作代码

<script>
    $(document).ready(function() {
        $("#contact-form").submit(function() {
            $("#loading").show().fadeIn('slow');
                $("#response").hide().fadeOut('slow');
                 var frm = $('#contact-form');
                 $.ajax({
                     type: frm.attr('method'),
                     url: 'url.php',
                     data: frm.serialize(),
                     success: function (data) {
                         $('#response').html(data);
                         $("#loading").hide().fadeOut('slow');
                         $("#response").slideDown();
               }, error: function(jqXHR, textStatus, errorThrown){
              console.log(" The following error occured: "+ textStatus, errorThrown );
            } });
           return false;
        });
    });
</script>

#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form

#loading可以是一个图像或在表单处理时要显示的内容,使用代码只需创建一个带有ID联系表单的表单

#6


0  

Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:

避免提交表单的另一种方法是将按钮放在表单之外。我有现有的代码正在工作,并根据工作代码创建了一个新页面,并编写了这样的html:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
    <button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>

This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.

该形式导致上述不期望的重定向。将html更改为下面显示的内容可解决问题。

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

#7


0  

I expect anyone to understand my idea very well as it's a very simple idea.

我希望任何人都能很好地理解我的想法,因为这是一个非常简单的想法。

  1. give your required form itself an id or you can get it by any other way you prefer.

    将您所需的表格本身作为身份证明,或者您可以通过您喜欢的任何其他方式获得。

  2. in the form input "submit" call an onclick method from your javascript file.

    在表单输入“提交”中从您的javascript文件调用onclick方法。

  3. in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
    To clarify that see this:

    在这个方法中,一个变量引用你的from id和addEventListener,并在“提交”上创建一个preventDefault方法而不是“click”。澄清一下,看到这个:

    // element refers to the form DOM after you got it in a variable called element for example:
    element.addEventListener('submit', (e) => {
       e.preventDefault();
       // rest of your code goes here
    });  
    

    The idea in brief is to deal with the form by submit event after dealing with submit button by click event.

    简单的想法是在点击事件处理提交按钮后通过提交事件来处理表单。

Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.

无论你在这个方法中需要什么,它现在都可以正常工作而不需要刷新:)只要确保以正确的方式处理ajax就可以了。

Of course it will work only with forms.

当然它只适用于表格。