0

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?

Community
  • 1
  • 1
user1128677
  • 479
  • 2
  • 11
  • 18

2 Answers2

1

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

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

If you want the to wait for return your values from the callback functions. Here you should call form_send() from the success callback to make it wait for the asynch call. And you can actually make it much simpler without checkC() also. Change the code a bit and use done and fail promises:

var formValidate = function () {
  var url = 'someurl';

  $.get(url)
        .done(function (data) {
            if (data.indexOf('OK') == -1) {
                console.log("error");
                return;
            } 
            form_send();
        })
        .fail(function () {
            console.log("error");
            return;
        })
}
Jaqen H'ghar
  • 16,186
  • 8
  • 49
  • 52
1

You can't do this since $.get is called asynchronously.

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) {
      // this return to this enclosing callback function but not formValidate
      if(data == 'OK') return false;
   });

   //this is the only return statement for formValidate function
   return true;
}

A workaround i suggested is just call your form_send() in the callback, for example,

form.on('submit', formValidate);

And for your formValidate,

var formValidate = function () {
    var url = "someurl";
    $.get(url, function( data ) {
      if(data.indexOf('OK') == 0) {
          form_send();
      }
    });
};
hylimR
  • 393
  • 4
  • 10