Reputation: 73
I'm trying to do data validation at beforeSend
. This data validation should return either true or false. The data is received from asynchronous filereader.onloadend
If false, the function shouldn't proceed. But with code below, it actually proceed POST
.
var checkValidity = function(data, callback){
const filereader = new FileReader()
filereader.onloadend = function(e) {
callback(e); // I want to do validation on data received here
}
};
$('#imageField').on('change', function(e) {
var formData = new FormData();
$.ajax({
data: formData,
type: 'POST',
beforeSend: function() {
var data = formData.getAll('inputField');
checkValidity(data, function(e){
// if console.log(e) here, actually return expected value
// I'm trying to return false/true here
e ? return true : return false
});
}
});
});
Upvotes: 0
Views: 117
Reputation: 50291
Call the ajax only after successful validation
var checkValidity = function(data, callback) {
const filereader = new FileReader()
filereader.onloadend = function(e) {
callback(e); // I want to do validation on data received here
}
};
$('#imageField').on('change', function(e) {
var formData = new FormData();
var data = formData.getAll('inputField');
checkValidity(data, function(e) {
e ?
return true: return false
});
If(conditionToCheckIfValid) {
$.ajax({
data: formData,
type: 'POST',
// rest of the code
});
}
});
Upvotes: 3