user1128677 user1128677 - 5 months ago 98
jQuery Question

jQuery: wait until $.get() return the value

This is my code example

var formValidate = function() {
var url = 'someurl';
var checkC = function (url, callback) {
$.get(url, function( data ) {
if(data.indexOf('OK') == 0) return callback('OK');
})
};
checkC(url, function(data) {
if(data == 'OK') return false;
});
return true;
}


My code is pretty similar to Adam Rackis's in this question Wait for jQuery $.get function to finish before running code. But unfortunately function dont wait for the data return. formValidate() just return true. I want use this function to check some conditions before sending data to server from form

form.on('submit', function(){
if(formValidate()) form_send();
})


Can someone tell me where was I wrong in code above?

Answer

The biggest problem is that formValidate() return true synchronously regardless to the ajax request.

var formValidate = function() {
  .
  .
  .
  return true;
}

You can actually make it much simpler without checkC() if you change the code a bit and use done and fail promises:

$.get(url)
        .done(function (data) {
            if (data.indexOf('OK') == -1) {
                return false;
            } 
            return true;
        })
        .fail(function () {
            return false;
        })
}
Comments