Secure Secure -4 years ago 172
jQuery Question

How to get return value from ajax function into a variable?

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download