How to use data outside of function returned from POST or GET method of jquery?
My question is i'm getting some data through jquery post method.. the problem is whenever i get data i'm just able to use that within function actually i want that data to use outside of function.. as i alerted data outside function it's not working...
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
$.post("getLatLan.php", {userid: uid}, function(data) {
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
alert(data[1]["latitude"]); //this is actually not alerting.. what is the reason ?
});
}
How to use data outside of function returned from POST or GET method of jquery?
My question is i'm getting some data through jquery post method.. the problem is whenever i get data i'm just able to use that within function actually i want that data to use outside of function.. as i alerted data outside function it's not working...
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
$.post("getLatLan.php", {userid: uid}, function(data) {
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
alert(data[1]["latitude"]); //this is actually not alerting.. what is the reason ?
});
}
Because data variable is out of scope at that point. Code below will assign the data to the local recievedData and you can use it out of the handling function scope. Though you will still be only able to access recievedData variable only when request is done.
$(document).ready(function() {
var recievedData;
var uid = $(".track_textbox").val();
var promise = $.post("getLatLan.php", {userid: uid}, function(data) {
recievedData = data;
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
promise.done(function() {
alert(recievedData[1]["latitude"]); });
});
this is a bit better...
This way you dont miss the execution. If you wrap your code into a closure, you can call it later too. So even though your "getlatlanfromjs" has already executed, your alertFn still exists and will be called when the $.post
is done.
function getlatlanfromjs() { $(document).ready(function() { var uid = $(".track_textbox").val();
var alertFn = function(data) { alert(data[1]["latitude"]); }; $.post("getLatLan.php", {userid: uid}, function(data) { var i; for (i = 1; i < 2; i++) { initialize(data[i]["latitude"], data[i]["longitude"]); } alertFn(data); }, "json"); }); }
var mydata = null;
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
$.post("getLatLan.php", {userid: uid}, function(data) {
mydata = data;
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
if(mydata != null) alert(data[1]["latitude"]);
});
}
All you needed to do was keep track of the scope of data.