Overriding variable value inside the $.get()
Starx’s Question:
I am facing a quite Strange problem, I dont seem to be able to override variable jSonData
from inside the success function of $.get()
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
if(typeof data !== 'object') {
if(settings.debug) console.log('Getting configuration settings from: ', data);
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here
}, 'json');
}
console.log(jSonData); // Gives the same value as it was before
};
Note: The success event of the $.get() is triggered
By the time you logged the value, the $.get()
has not overridden jSonData
yet since the AJAX request has not returned by that time. Do the console.log
inside the function instead.
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here - You just did!
console.log(jSonData);
}, 'json');
I was having that problem because AJAX calls are asynchronous and thus the call would not have been completed when console.log()
was executed.
Solution I used to fix my issue was by using deferring methods.
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
var getData = function() {
if(typeof data !== 'object') {
return $.get(data, 'json');
}
else { return jSonData; }
};
getData().done(function(result) {
jSonData = result;
console.log(jSonData); // Gives the same value as it was before
}).fail(function() {
//
});
};