Skip to content Skip to sidebar Skip to footer

How To Return Value In Ajax Call?

I want after keyup in input if data was 0 return is false if was not false return is true. but in my try always return is true in case data === 0: $('input').live('keyup change', f

Solution 1:

The .ajax() call returns at an arbitrary time in the future. The keyup and change handlers return (essentially) immediately.

Do the work in your success handler. Alternatively, you could set a global (or namespaced global) to the returned value, with the understanding that it would be invalid until the Ajax call completes.

You also need to make sure the data being returned is what you expect it to be, if the if statement itself isn't doing what you expect. That's a different issue than the return value from the event handler.

Solution 2:

I see that you've selected async: false as your answer, but there is a better way - using a callback function.

$('input').live('keyup change', function () {

  DoSomething(function(result) {
   // this isn't blocking
  });    

})

functionDoSomething(callback) {

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'search_customer',
        data: dataObj,
        cache: false,
        success: function (data) {

          var result = data !== 0;

          if (typeof callback === 'function') {   
            callback(result); 
          }    

        }
    });

}

Post a Comment for "How To Return Value In Ajax Call?"