简体   繁体   中英

How to return boolean in Ajax call with data received from async function

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
            });
        }
    });
});

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 
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM