jQuery page redirect after submit the form

2020-03-24 07:50发布

问题:

I have a form like this

<form id="add-to-cart" name="my-form" action="http://www.example.com" method="post">
  <div class="row flat">
    <input type="hidden" name="cartkey" value="">
    <input type="hidden" name="id" value="2">
    <button type="submit"  value="submit" data-value="2" data-name="id">Buy Now</button>
  </div>
</form>

To Save the form I have used jQuery. So for now my code looks like this

 <script type="text/javascript">
    jQuery(document).ready(function() {
      jQuery('button').click(function(){
        var Value = jQuery(this).attr('data-value');
        jQuery('[name="id"]').val(Value);
        jQuery('#add-to-cart').submit();
        window.location = "http://www.page-2.com";
        });
    });
  </script>

But here after submit the form is not redirecting to another page(http://www.page-2.com). So can someone kindly tell me how to do redirect the form after submit the form?

Update Sorry here I can't use ajax. I want to submit the form in simple.

回答1:

If you don't use ajax, the form will be submitted, and the browser redirected to the action url of the form. The only way to do a redirection after the submit, is to do it in the handler of the action form. You could however add a parameter with the URL you want to redirect to.

The only advantage of that solution over a solution involving ajax is that no javascript is required. It would work whether javascrit is enabled or not.



回答2:

You can handle this in your action, you calling onSubmit() from server code redirect it to the page you want.

Or you need to use ajax post() calls which give you onSuccess and onFailure events on call complete. Something like this:

$('#add-to-cart').submit(function() {
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: 'json',
        success: function(json) {
           window.location.href = "http://www.page-2.com";
        }
    })
    return false;
});


回答3:

I did it this way:

html:

                    <form action="javascript:searchItem();">
                        <div class="searchbox">
                            <div class="search-inner">
                                <div class="item-input">
                                    <input type="text" id="itemName" placeholder="Search Product" required/>
                                </div>
                                <div class="item-after">
                                    <input type="submit" value="" class="button-search"/>
                                </div>
                            </div>
                        </div>
                    </form>

Javascript:

function searchItem() {

    $.ajax({
        url: urlDomain + "pricelist/?itemName=" + $("#itemName").val(),
        type: "GET",
        headers: {"Accept": "application/json", "Content-Type": "application/json"},
        success: function(data) {
            // do your work on success and then,
            location.href = "path/to/next/Page/To/Display.html";
        },
        error: function() {
            alert("error");
        }
    });
}

I wrote above code for getting values from server, but you can change jQuery "Type" parameter to "POST" and add "data" parameter with its values you want to be sent to server.

Hope it helps you...



回答4:

Disable the form submission using onsubmit="return false;"

html

<form id="add-to-cart" name="my-form" action="http://www.example.com" method="post">

js

<script>
      $(document).ready(function() {
          $('button').click(function(){
             var form = $(this).parents('form');

             $.ajax({
                 type: 'POST',
                 url: $(this).attr('action'),
                 data: form.serialize(),
                 dataType: 'json',
                 success: function(response) {
                      window.location.href = "http://www.page-2.com";
                 }
             });
             return false;
           });
      });
</script>

keep the action attribute value as a fallback, so you'll be sure that your form will work correctly even if javascript is enabled or not on the client side.



回答5:

I know that this is an old question, but I found a different way to redirect after submitting a form.

First of all, to reiterate the basics of the <form> tag since the OP was literally a NewUser, submitting a form has redirecting built into it. If you change your original html from:

<form id="add-to-cart" name="my-form" action="http://www.example.com" method="post">

to:

<form id="add-to-cart" name="my-form" action="http://www.page-2.com" method="post">

then clicking on your submit <button> will automatically redirect you.

However, maybe NewUser wants submitting the form to always stay on www.example.com and only sometimes redirect to www.page-2.com, once the submission is complete? I ran into this exact scenario at work today.

In my case, we had a form that consisted of data in a table. Users could make changes to the data and then click the submit button (called "Save") to save the changes in the database. The action of <form> just refreshed the form/table page because we wanted users to stay on that page.

We also had a link on that page that would take you to another page, but I had to make sure that it autosaved all the data before redirecting. So I made the link submit the form, and then redirect. This was accomplished with jQuery, and without Ajax. Here it is, adapted to NewUser's code:

(<form> is unchanged, action="http://www.example.com")

<script type="text/javascript">
$(document).ready(function() {
  // The link has class="linky-link" for easy selecting and href="http://www.page-2.com".  I did not use an id because I had multiple nearly identical links on the same page.
  $(".linky-link").on("click", function(e) {
    e.preventDefault();  // Don't redirect yet!
    var $form = $("#add-to-cart");  // $form instead of form because it's shorthand for a jQuery selector - not strictly necessary, but helpful
    $form.append("<input type='hidden' name='link_redirect' value='" + this.href + "'>");  // This is added to the end of the form and triggers the redirect after the saving is done
    $form.submit(); // Submitting the form saves the data, and then redirects
    });
});
</script>

(Note: be sure this bit of JavaScript is located at the very bottom of the php file, once everything else is loaded)