I have an HTML multipart form, with name, email and file upload.
I want to register the user with Ajax first of all. If registration succeeds, I want to then proceed to submit the form. If it fails, I want to avoid submitting the form.
This is my code:
--- HTML ---
<form id="account-form" method="post" enctype="multipart/form-data" data-ajax="false" action="upload.php" >
<input type="text" name="username" id="username" />
<input type="email" name="email" id="email" />
<input type="file" id="mediaupload" name="mediaupload" accept="image/*" />
</form>
--- JavaScript ---
accountform.submit(function(event) {
var registration_ok = true;
// See if we can register the user
// And if we can, submit the form.
$.ajax({
type: "POST",
url: "/usercreate.php",
data: postdata,
dataType: 'json',
success: function(data) {
// fine to submit the form.
},
error: function (data){
// If this fails, we don't want to submit the form!
registration_ok = false;
}
});
return registration_ok;
});
However, it’s always returning true – I guess this is because the main function returns before the Ajax error is called.
How can I prevent it from returning true, and submitting the form, when registration fails?
Thanks!
You need to return false always, instead of
registation_ok, and then in the success function, go:i.e. never submit the form when you press the submit button, wait for the AJAX to return, and then only submit the form if the registration was successful.