简体   繁体   中英

How can i submit and redirect a form using jquery

I want to submit and redirect a form using jquery.I have tried to do it but redirect does not works, here is my code. The problem is i have two submit buttons in my form and both are redirecting to other page when i set the action=".....php".But i do not want update cart button to redirect to any other page so i want to use jquery for submitting and redirecting form. Please give me some solution. Thanks...

<script type="text/javascript">
 $(document).ready(function(){
     $('#updateCart').click(function(){
    $('#form1').submit(); 
     window.location.href='Checkout.php';

                           });
 });
</script>

<form name="form1" method="post" id="cartform" class="clearfix" action="#">

<input type="submit" id="updateCart" value="Update Cart" class="btn-txt" name="update" onclick="update_cart()"> 
<input type="submit" class="checkout-button btn" name="checkout" />

</form>

You should do e.preventDefault(); on the update cart button and then fire the function that updates the cart.

Something like this:

<script type="text/javascript">
$(document).ready(function(){
    $('#updateCart').click(function(e){
        e.preventDefault();
        updateCart(); 
    });
});
</script>

You wouldn't want to fire the form submission when the "update cart" button is pressed, only when the "checkout" button is pressed.

You could just make it an html button that doesn't submit by setting it's type to "button" and then it will just run the javascript when clicked. Then you can put the action attribute back on your form and it will only submit for the checkout submit button.

<button type="button" id="updateCart" class="btn-txt" name="update" onclick="update_cart()">Update Cart</button>

Your approach is OK but you need to decide which button is your official form "submit" button, and which is attached to a jQuery function to update the form before submitting.

I would recommend that you don't do any javascript for your main "Checkout" button as you will want this to go to a payment page where you capture payment details - ie the form will follow it's action="checkout.php" .

For your "Update Cart" button follow APAD1's answer and adapt it to your needs. If you're going to be updating form fields you'll need to think about using JSON-encoded returned data...

add id or class in form tag

<form id="form1" ...>

change submit button to anchor

<a id="submitAnchor"> ... </a>

and in javascript submit the form and redirect the user as well

$("#submitAnchor").click(function(){
            $(".form1").submit();
            setTimeout(function() {
                window.location = 'your URL';
            }, 1000);
        });

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