$(function(){
var bwr_w = null; //global variable
//below function gets the dynamic data
function myfunc() {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year="+val ,
cache: false,
success: function(result){
bwr_w= result.replace(/\s+/g, ''); //want to set the data again
}
});
}
myfunc(); //my dynamic function gets called
$(".container_map").mapael({
map : {
name : "usa_states"
},
plots: {
bwr_w //this should work as per myfunc()
}
});
});
I am always getting bwr_w value as null even if I get a some value in ajax return I want my bwr_w to be set as global variable so that when I get some result from ajax it should change my map pins.
The issue is because the $.ajax
call is asynchronous. This means that your myfunc
is exited before the data is returned from the AJAX call. To fix this issue, put all code dependent on the returned data within the callback:
$(function () {
var bwr_w = null; //global variable
//below function gets the dynamic data
function myfunc() {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year=" + val,
cache: false,
success: function (result) {
bwr_w = result.replace(/\s+/g, ''); //want to set the data again
$(".container_map").mapael({
map: { name: "usa_states" },
plots: { bwr }
});
}
});
}
myfunc();
});
If you want different logic executed on each call to myfunc
pass it in as a callback function:
$(function () {
//below function gets the dynamic data
function myfunc(callback) {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year=" + val,
cache: false,
success: function (result) {
var bwr_w = result.replace(/\s+/g, ''); //want to set the data again
callback(bwr_w);
}
});
}
myfunc(function (bwr) {
$(".container_map").mapael({
map: { name: "usa_states" },
plots: { bwr }
});
});
});