I trying to making form validation using JavaScript + AJAX, but it’s not working.
What I am gonna wrong plz solve my problem.
function validateform() {
$.ajax({
url: '../api?type=validate_refercode&refer_code=' + $('#refer_code').val() + '',
success: function(data) {
if (data == 'fail') {
return false;
}
}
});
return true;
}
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<form method="POST" onsubmit="return validateform()">
<div class="col-lg-6">
<div class="floating-label form-group">
<input class="floating-input form-control" type="text" id="refer_code" placeholder=" ">
<label>Referral Code</label>
</div>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-white">Sign Up</button>
</form>
2
Answers
Use
event.preventDefault()
because the form is getting submitted before the AJAX request is completed and the success callback is executed.Some will complain about my abstractions; but, this is the layout i typically use for JS. It allows you to add more functions to it if needed.
Avoid using inline functions and use eventlisteners instead. Inline functions will likely break your CSP (which protects you from XSS) and inline don’t stack whereas eventlisteners do.
Also use html validation by using "pattern" or "required".
My example uses pure JS and doesn’t need jQuery.