Sangit Sangit - 5 months ago 47x
Javascript Question

Submit form only after ajax verification success

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

var data = $(this).serialize();

type: "POST",
url: "/cart/check",
data: data
if (data.success == true) this.submit();

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


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.

    context: this, //<-- the form