简体   繁体   English

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

[英]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: 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: 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.我无法做的是在按下#form-button-submit时阻止页面刷新。 I tried return false;我试过return false; I tried preventDefault() and every combination including return false;我尝试preventDefault()和每个组合,包括return false; inside the onClick . onClick内部。 I also tried using input type="button" and type="submit" instead and same result.我还尝试使用input type="button"type="submit"来代替,结果相同。 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.我非常感谢您在这方面的帮助。

Modify the function like this: 像这样修改函数:

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

And as comment mentions, pass the event: 正如评论所提到的,通过事件:

onclick = sendForm(event);

Update 2: 更新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);
      }
    });
});
function sendForm(){
    // all your code
    return false;
}

Have you tried using 您是否尝试过使用

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

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! 尝试使用XHR将请求发送到任何URL,而不是$ .ajax()...我知道这听起来有些怪异,但是请尝试一下!
Example- 例-

<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. 这将成功发送您的数据...而无需重新加载页面。

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为contact-form

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>

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. 给您所需的表格本身一个ID,或者您可以通过其他任何方式获得它。

  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". 在此方法中,使变量从id引用您的addEventListener,并在“提交”而不是“点击”上创建preventDefault方法。
    To clarify that see this: 为了澄清这一点,请参见:

     // 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. 当然,它仅适用于表单。

The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. 我的处理方式:我删除了整个form标签,并将所有表单元素(例如input,textarea标签)放置在div并使用一个按钮调用了javascript函数。 Like this: 像这样:

<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
                            onclick="javascript:sendRequest()">Save
                            changes</button>
<div>

Javascript: Javascript:

function sendRequest() {

        $.ajax({
            type: "POST",
            url: "/some/url/edit/",
            data: {
                data: $("#myform textarea").val()
            },
            success: function (data, status, jqXHR) {
                console.log(data);
                if (data == 'success') {
                    $(`#mymodal`).modal('hide');
                }
            }
        });

        return true;
}

I thought why use a form when we are sending the actual request using AJAX. 我想过,为什么要在使用AJAX发送实际请求时使用form This approach may need extra effort to do things like resetting the form elements but it works for me. 这种方法可能需要额外的精力来完成重置表单元素之类的工作,但对我有用。

Note : The above answers are more elegant than this but my use case was a little different. 注意 :上面的答案比这更优雅,但是我的用例有些不同。 My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. 我的网页有很多表格,我认为向每个提交按钮注册事件侦听器不是一个好方法。 So, I made each submit button call the sendRequest() function. 因此,我使每个提交按钮都调用了sendRequest()函数。

@Yashas : the most viable solution after trying out all sort of event binding and calling event.preventdefault, etc, etc. @Yashas:尝试各种事件绑定并调用event.preventdefault等后,最可行的解决方案

on removing the tag, page refresh worries were no longer valid. 在删除标签后,页面刷新后的担忧不再有效。 However, the form styling in the page got impacted slightly. 但是,页面中的表单样式受到了一些影响。

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

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