I had trouble implementing parsley.remote.js because of AMD in our require configuration.
I'm trying to implement a custom validator that does an AJAX request and returns true or false based on the response.
Problem is, I keep getting a response of false regardless of what the AJAX request returns.
Why does this code never work?
window.ParsleyValidator.addValidator('cardcode',
function (value) {
var valid = false;
$.ajax({
url: '/data/checkout/cvvCheck.json',
data: {
cvv: value
},
success: function(response) {
if(response.valid === true) {
return true;
}
else {
return false;
}
}
});
}, 32);
<input type="tel" name="card-code" id="card-code" maxlength="4" required="" data-parsley-required="true" data-parsley-required-message="Please enter the cvv" data-parsley-type="number" data-parsley-type-message="Please enter a valid cvv" data-parsley-cardcode="true" data-parsley-cardcode-message="Please ensure you are entering the correct cvv." data-parsley-id="65">
The problem is that the AJAX call to your remote validator is being made asynchronously and that means that your response is coming back too late for Parsley, so it will always assume a false result for the validation.
While synchronous AJAX calls should be avoided, if you add the async: false option to your AJAX call your code should work:
window.ParsleyValidator.addValidator('cardcode',
function (value) {
var valid = false;
$.ajax({
url: '/data/checkout/cvvCheck.json',
data: {
cvv: value
},
async: false,
success: function(response) {
if(response.valid === true) {
return true;
} else {
return false;
}
}
});
}, 32);
Here's an asynchronous method that I found that worked for me - you'll need to load parsley.remote.min.js instead of parsley.min.js, then setup a custom remote validator using this code:
window.Parsley.addAsyncValidator('cardcode', function (xhr) {
var response = xhr.responseText;
if (response.valid === true) {
return true;
} else {
return false;
}
}, '/data/checkout/cvvCheck.json');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With