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!
3
Answers
Is
$('myform')
a typo? Should it be$('#myform')
?#idName
..className
name
$('myform')
is looking for a<myform></myform>
element.$('#myform')
is looking for a<... id="myform"></...>
$('.myform')
is looking for a<... class="myform anotherRandomClass"></...>
You need to
return false
, otherwise, the function with carry on with the default behaviour after the function is complete:Update: looking at the jQuery documentation, I don’t know if
return false
is necessary ife.preventDefault()
is present.Your form is submitting normally because your jquery selector is wrong. You have to change
$('myform')
to$('#myform')