Why is this marked as a duplicate for how to get a response from AJAX? I got the response in the callback function?
I'm using AJAX with PHP to check if a user's authorisation code (basically a password) is valid. This works in so far as it doesn't allow the form to be submitted if the user's input is incorrect against the stored database value. However, it also doesn't allow form submission when correct, despite the JS reaching the callback function and changing the input class's styling to indicate the input is correct.
<form name="auth_form" id="auth_form" method="post" action="auth-action.php">
<p>Please enter authorisation code.</p>
<div style="width:400px;" class="form-group has-feedback" id="feedback" name="feedback">
<input class="form-control" id="authcode" autocomplete="new-password" name="authcode" type="password" required>
<span id="glyph" name="glyph" class="glyphicon form-control-feedback"></span>
</div>
</div>
<button class="btn btn-primary" name="submit" type="submit">Submit</button>
</div>
</form>
$(document).ready(function() {
$("#authcode").blur(function(e) {
if (!checkValid()) {
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) {
if (!checkValid()) {
e.preventDefault();
}
});
});
function checkValid() {
var authcode = $("#authcode").val();
$.ajax({
url: 'auth-action.php',
type: 'POST',
data: { 'authcode' : authcode },
success: callback
})
}
function callback(response) {
var data = response;
var IsValid = false;
if (data.indexOf("success") > -1) {
$('#feedback').addClass('has-success');
$('#glyph').addClass('glyphicon-ok');
$('#feedback').removeClass('has-error');
$('#glyph').removeClass('glyphicon-remove');
IsValid = true;
} else {
$('#feedback').addClass('has-error');
$('#glyph').addClass('glyphicon-remove');
$('#feedback').removeClass('has-success');
$('#glyph').removeClass('glyphicon-ok');
IsValid = false;
}
return IsValid;
}