2

I'm calling a function and I want to get back some value. But I didn't get any value.

How can I use the return value?

$(function () {
    $(".datepicker").datepicker({
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [array.indexOf(string) == -1]
            console.log(array.indexOf(string) == -1);
        }
    });
});
var BDate = gateDateBooking(); // Calliing a function 
var BookingDate = Bdate; // But i did't get any responce here
function gateDateBooking(){
    $.ajax({
        url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
        type: "POST",
        dataType: "text",
        cache: false,
        success: function (data) {
           alert(data);
          return data; // return responce 
       }
   });
 }
5
  • You can't return a value from the middle an an asynchronous callback. The will return to the success caller. Commented Oct 30, 2014 at 9:35
  • You can accomplish it by setting async false, but its not preferred. Better to execute (what you want) inside success callback function only. Commented Oct 30, 2014 at 9:35
  • So there no other option to access this return value> some other option to use this value Commented Oct 30, 2014 at 9:41
  • I have updated below to show two possible alternatives that let you retain gateDateBooking as a separate function. Commented Oct 30, 2014 at 9:49
  • 1
    I hate to tell you this, but you have chosen the worst possible solution to your problem. Never use async: false. Learn how to work with async patterns. Reasons why outlined in answer below. Commented Oct 30, 2014 at 10:04

4 Answers 4

12

You can't return a value from the middle an an asynchronous callback. It will return the value to the success caller (which is inside the ajax code).

Although it would appear to "work" you should never consider using the ajax async: false option as

  • a) it will cause more trouble than it is worth
  • b) it will stall the browser and
  • c) it is just not the correct way to work with asynchronous events.

Instead you can either use a callback passed to the gateDateBooking function, or use jQuery promises (or just place your code in the success callback - but this is not flexible):

A callback version would look like this:

gateDateBooking(function(data){
    var BookingDate = data; // Do something with the data when it is ready
});

function gateDateBooking(cb){
    $.ajax({
        url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
        type: "POST",
        dataType: "text",
        cache: false,
        success: function(data){
            // call the callback passed
            cb(data);
        }
   });
}

This is an example using the Ajax promise that $.ajax returns.

gateDateBooking().done(function(data){
    var BookingDate = data; // Do something with the data when it is ready
});

function gateDateBooking(){
    // return the ajax promise
    return $.ajax({
        url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
        type: "POST",
        dataType: "text",
        cache: false
   });
}
Sign up to request clarification or add additional context in comments.

Comments

2

The Ajax call that you're using is an anonymous function, it has it's own scope and the return is returned to "nowhere". In order to return the value from an asynchronous method you should use a callback:

function gateDateBooking(callBack){
$.ajax({
    url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
    type: "POST",
    dataType: "text",
    cache: false,
    success: function (data) {
      callBack(data);
    }
  });
}

and then use the call like this:

gateDateBooking(function(data){
    var BDate = data;
    var BookingDate = Bdate;
    //continue your function here, inside of the callback
});

This ensures that the values are set from the response of your Ajax call. Synchronous calls are deprecated as has been mentioned in the comments.

There's also the option to use promises instead of callbacks. You can read about both in the following links:

https://www.w3schools.com/jquery/jquery_callback.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

5 Comments

Never suggest aysnc: false as a solution. It causes more trouble than it solves. Always work with the async pattern (using callbacks or promises).
Glad I could help.. If you have time check out TheBlueAussie's solution. It's very good too..
Please don't say "very good too". You have just given a loaded gun to a small child to play with, without any warning :)
As of jQuery 1.8, the use of async: false is deprecated!
@mikwee Updating to a callBack.. Hold on. Thanks, by the way.
0

make a global var and then in your success do

success: function(data) {
      global_var =data;
},

you can use deffered to display it then

1 Comment

Introducing deferred to a newbie without explanation is not helpful. Best you provide a proper example.
0

The success function is called from somewhere inside the $.ajax function and $.ajax does not return it because of it's asynchronous nature (by default). You could use a global variable where you put the returned value inside your success handler function.

alert(data);
return data;

I suppose alert displays the right thing? Just remove the "return data;" and replace it by eg. "BookingDate = data;"

1 Comment

sorry for asking this qus, but how can i make global variable of data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.