简体   繁体   中英

How to use jQuery to submit a form and then reload the page

I'm trying to figure out if this is possible.

I have Page-A that has Form-Foo with an action to Bar in a new window.

Upon clicking submit, I'd like the form to submit AND Page-A to reload.

So far I can only get one or the other to work...any pointers would be appreciated.

In addition to DudeSolutions solution...I tried this:

$(document).ready(function() {
    $('#foo').submit(function() {
        $.post('bar.asp', $(#foo).serialize(), function(data) {

                window.location.reload();

        });

    });
});

Same results...I can get the form to submit and a new tab opens...but Page-A does not reload.

If you intend to submit the form and reload the page, that would be the default behaviour, and only the url in the action attribute is incorrect. If so just change the URL, no need for ajax if a new pageload is intended anyway :

$(function() {
    $('#Form-Foo').attr('action', 'Page-A url');
});

or:

$(function() {
    $('#foo').on('submit', function(e) {
          e.preventDefault();
          setTimeout(function() {
               window.location.reload();
          },0);
          this.submit();
    });
});

Just queueing the reload should be enough to wait until after the form is sent to reload the page, but as most browsers stop the timeout when you leave the browser tab, it won't really reload until you go back to that tab, but that should be unnoticeable.

Here's an idea:

  <script type="text/javascript">
    $("#my_form").submit(function() {
      $.ajax({
        type: "POST",
        url: "/path/to/post/handler/",
        data: $("#my_form").serializeArray(),
        success: function() {
    top.reload();
        }
        });
    return false;
});</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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