0

I am having this html code:

<form class="add-to-cart-form">
         <input type="hidden" name="product-code" value="2" />
         <input type="submit" value="Add" class="button" onclick="addToCart('2');"/>
    </form>

And a javascript code:

function addToCart(product_id, quantity) {
        quantity = typeof(quantity) != 'undefined' ? quantity : 1;

        $.ajax({
            url: 'test.php',
            type: 'post',
            data: 'product_id=' + product_id + '&quantity=' + quantity,
            dataType: 'json',
            success: function(json) {
                alert(json.message);
            }
        });
    }

IN the html file anytime, I click on the submit button, instead of taking me to the function addToCart, the form is submitted.

I am new to javascript and really don't know the source of the problem. Kindly help me solve this problem.

4
  • 3
    change type submit to button Commented Jul 15, 2016 at 3:03
  • hardly see reason for having form since you don't reference any of the inputs in it. But basic issue is doing ajax doesn't tell browser not to submit the form through default browser process Commented Jul 15, 2016 at 3:04
  • add return false to onclick attribute Commented Jul 15, 2016 at 3:14
  • @charlietfl the reason is progressive enhancement Commented Jul 15, 2016 at 11:16

1 Answer 1

1

Clicking a submit button has a default action of submitting the form. If that's not what you want to do, you have to prevent it.

<form class="add-to-cart-form">
     <input type="hidden" name="product-code" value="2" />
     <input type="submit" value="Add" class="button" onclick="event.preventDefault();addToCart('2');"/>
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of preventing the default action, we can just change the type of the input element to button (as suggested in one of the comments).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.