JavaScript: control logic for Ajax call before form submit?
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(eve开发者_如何学JAVAnt) {
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:
document.forms["account-form"].submit(); //edited
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.
Why not just submit the form programmatically in the onSuccess handler in your .ajax statement?
Something like this:
document.forms["account-form"].submit();
you can make syncronic ajax call, just add the async: false, parameter
Sorry I misunderstood the question. inside of your success method trigger the form.submit();
The problem is that the AJAX call is asynchronous, so the success
and error
functions won't be called until after the function has returned the registration_ok
value (which you pre-set to true
).
精彩评论