I have a situation where I want to have a global variable like a whose value I'll be fetching from jQuery Ajax from some server and then want the value to be available on call from other function. To visualize:
var a = [];
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'some url',
success: function (response) {
a = response.somearray;
},
error: function () {
alert("Not successfull");
}
});
});
function something() { // this function will be called onclick of a button in html
console.log(a); // here I want the value that came from the server. But currently, it's printing empty array
}
What I have tried are as follow:
- Removing var keyword from (a) to make it global.
- Assigning no value (here empty array) to (a) declaration above (that turned out to be a blunderous mistake though).
- Removing (a) declaration completely from the top.
The thing to take care about is that something() function is being called from an HTML button on complete page load and after ajax call. So value is already available.