adam78 adam78 - 1 month ago 10
Ajax Question

jQuery Ajax Post - Unable to set global variable using callback function?

I have the following ajax method. On success I want to set a global variable but it doesn't seem to work - console returns empty object. It only works if I define async to false. However I'd like to keep the ajax method asynchronous. How can I get this to work?

var appointment = {};

if ($("#Appointment").is(":checked")) {
$.ajax({
type: "POST",
url: "someurl",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
dateStart: moment()
}),
// async: false,
dataType: "json",
success: function(data) {
ajaxCallBack(data);
}
});

function ajaxCallBack(data) {
var response = $.parseJSON(data.d);
appointment = { startDate: response.startDate, endDate: response.endDate };
}
}

console.log(appointment);

Answer

ajax is an asynchronous operation. So console.log will execute even before ajax success. console the variable from ajaxCallBack function

function ajaxCallBack(data) {
  var response = $.parseJSON(data.d);
  appointment = { startDate: response.startDate,
                  endDate: response.endDate };
  console.log(appointment);
}