I would like to pass my AJAX response on success, basically after the content has been loaded, to a javascript variable which I can eventually utilise perhaps in other functions. I have this code which works:
var json; // Variable with Global Scope
$.ajax({
type: "GET",
url: "http://127.0.0.1:8888/...",
dataType: "JSON",
async: false,
success: function (response) {
json = JSON.parse(response.value1); // value1 as in {"value1":1234} from the url.
console.log("Json Parse Data 1: " + json);
}
});
console.log("Json Parse Data 2: " + json);
According to my research, the use of async: false
is deprecated given that it freezes the browser load until the AJAX Request is complete. So, an alternative to this would be the following:
function getValue(callback){
var json;
$.ajax({
type: "GET",
url: "http://127.0.0.1:8888/...",
dataType: "JSON",
success: function (response) {
var json = JSON.parse(response.value1);
console.log("Json Parse Data 1: " + json);
callback(json);
}
});
}
function on_Complete(json) { // When request is complete, do this
console.log("Json Parse Data 2: " + json);
}
getValue(on_Complete); // Here I call the second function to do console.log("Json Parse Data 2: " + json)
This comes very close, but what I am trying to achieve with the second code is passing the var json;
as a callback and return its value to the second function after the request is successful instead of console.log("Json Parse Data 2: " + json)
. Some along lines this:
function on_Complete(json) {
var result = json;
return result; // Or directly return json;
}
var value1 = getValue(on_Complete); // Making this variable equal to json returned in on_Complete(json)
console.log("Json Parse Data 2: " + value1);
What am I missing?