This is using jQuery ajax and get data from php file.
I can see data that I want to have at first and second alert however, I do not know why I cannot see any value from the third alert.
function getMarkerContent(marker) {
// Fetch data from database
var ret = "<ul>";
var temp = "";
var process = "";
$.get("../status.php", function (returnValue) {
var json = eval("(" + returnValue + ")");
$.each(json, function (key, state) {
obj = state;
ret += "<li>" + obj.member_id + ": " + obj.content + "</li>";
temp += obj.member_id + ": " + obj.content + "\n";
});
process = processfunction(temp);
alert(temp); // first alert
ret += "</ul>";
});
alert(process); // third alert
}
function processfunction(data) {
alert(data);
return data; // second alert
}
Congratulations! You just discovered why callbacks exist.
http://api.jquery.com/jQuery.get/
Your first and second alert are triggered within the .get
success
callback function, and thus are called only after the AJAX method returns a result.
Your third alert takes place outside of the callback, so it is fired before the AJAX method returns any data.