0

I am returning Json obeject from back and try to bind the response in global variable. ** Returning from C# **

return Json(new
            {
                January = january,
                February = february,
                March = march
            });

** Here is my ajax calling function **

var responeOfData;
var feb; 
var mar;
$.ajax({
    url: "CashManagement/GetCashOverview",
    type: 'GET',
    dataType: 'json', // added data type
    success: function (res) {
        responeOfData = res;
        feb = res.february; // ** getting the value here **
        mar = res.march;
    }
});
var test = feb; **not getting the value here**

In the above code I declare a global variable responeOfData and try to set the result value but it won't work outside the ajax function then I declare 2 more global variable feb and mar and set the response value and it's showing the value inside the function and I have tried to assign it in a test variable outside the function it's showing nothing. What's wrong actually I can't understand.
Can anyone help me?

1 Answers1

3

Ajax requests are asynchronous, meaning the lines of code after the request aren't guaranteed to run after the request has finished, that's why the success callback exists, to place a code to run after a successful request.

which means this is the correct way to the what you want:

var responeOfData;
var feb; 
var mar;
var test; // declare globar variable test
$.ajax({
    url: "CashManagement/GetCashOverview",
    type: 'GET',
    dataType: 'json', // added data type
    success: function (res) {
        responeOfData = res;
        feb = res.february; // ** getting the value here **
        mar = res.march;
        
        test = feb; // assign value to variable
    }
});

In case you insist for the request to be synchronous, you can specify the async option and set it to false.

var responeOfData;
var feb; 
var mar;
$.ajax({
    url: "CashManagement/GetCashOverview",
    type: 'GET',
    dataType: 'json', // added data type
    success: function (res) {
        responeOfData = res;
        feb = res.february; // ** getting the value here **
        mar = res.march;
    },
    async: false // make ajax request synchronous
});
var test = feb; //feb exists;
Hagai Wild
  • 1,904
  • 11
  • 19