Reputation: 159
I'm trying to have an "add to cart" button only perform an actual submit (proceed to an added-to-cart page) if an ajax call comes back successful, otherwise display a message given in the ajax result and not actually perform the submit.
this is what i have so far
$("#addtocart").submit(function(event){
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "/cart/check",
dataType:"json",
data: data
}).done(function(data){
$("#message").html(data.message);
if (data.success == true) this.submit();
})
event.preventDefault();
});
if I remove event.preventDefault() the form always submits regardless of the check, if i leave it in, it never submits. Maybe this.submit() is not the right solution. I read somewhere that preventdefault should only be called if there was no success on the validation, but if i try
if (data.success == false) event.preventDefault();
it still submits the form no matter if data.success is true or false
i'd be ever so thankful if someone has a solution on how to do this right
Upvotes: 2
Views: 551
Reputation: 999
this
is not your form inside the callback, because this is usually set to the context of the caller, which is jQuery's code, not yours, for that callback. There are a few different ways that you can fix it:
Use the context
property of $.ajax
to set this
in your callback to whatever you want it to be - probably this
for you:
$.ajax({
...
context: this
})
Use $("#addtocart")
instead of this
. However, that is less extensible if you change your mind about the selector that you use, or you want to use the same code for multiple different forms.
Use event.target
(or $(event.target)
) to run code on the event's target, whatever element it happens to be. This means that you can still access the jQuery XHR object through this
if you decide that you still want to use it, though that might not matter to you at all.
Upvotes: 0
Reputation: 97672
this
inside the done callback is the jqXhr object not the form, if you want to bind the form as the context of the done function use the `context config.
$.ajax({
context: this, //<-- the form
...
Upvotes: 4