geekt
geekt

Reputation: 2646

How to prevent a page from refreshing when I want to submit a form?

I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful.

Here is my code:

html

<form action="{% url 'cart-add' %}" method="GET" id="myform">
     {% csrf_token %}
     <label>
        <input type="hidden" name="{{ product.pk }}">
        <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1">
        <button type="submit" value="">Add to chart</button>
    </label>
</form>

Ajax/JQuery script

<script type="text/javascript">
$(document).ready(function () {
    $('myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("myForm").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});
</script>

When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added.

Can somebody help me? Thank you very much for your time. I much appreciate it!

Upvotes: 0

Views: 102

Answers (3)

Darpan Kulkarni
Darpan Kulkarni

Reputation: 1400

Your form is submitting normally because your jquery selector is wrong. You have to change $('myform') to $('#myform')

<script type="text/javascript">
$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#myform").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});
</script>

Upvotes: 0

DemiPixel
DemiPixel

Reputation: 1891

Is $('myform') a typo? Should it be $('#myform')?

  • To reference a HTML's ID, use a #idName.
  • To reference a HTML class, use a .className
  • To reference a HTML element, just enter name

$('myform') is looking for a <myform></myform> element.

$('#myform') is looking for a <... id="myform"></...>

$('.myform') is looking for a <... class="myform anotherRandomClass"></...>

Upvotes: 1

Chris Happy
Chris Happy

Reputation: 7305

You need to return false, otherwise, the function with carry on with the default behaviour after the function is complete:

<script type="text/javascript">
$(document).ready(function () {
    $('#myform').on('submit', function(e) { // fix typo
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("myForm").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
        // Prevent function from saving
         return false;
    });
});
</script>

Update: looking at the jQuery documentation, I don't know if return false is necessary if e.preventDefault() is present.

Upvotes: 1

Related Questions