I want to get a value from JSON and use in a function, inside an Ajax request:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('device ready');
function Hi(img_url){
alert('Hi, the img_url is '+img_url);
}
}
$$.ajax({
type: "GET",
dataType: 'json',
url: target,
//Sucess
success: function(data){
var img_url = data.media.display_src;
Hi(img_url);
},
//Error
error: function(xhr,status){
alert("Error"+status+xhr);
console.log(xhr.response);
}
});
Hi()
Because your Hi
function is inside another scope. Every function
creates it's own scope, so what is defined in that scope
, is undefined
for another's. Move your function out from the onDeviceReady
function.
Example
Here you will see that innerFunction
and innerVariable
are undefined
, because they are not visible outside of outer
function.
function outer(){
var innerVariable = 'hello';
function innerFunction(){
console.log('inner function') ;
}
}
console.log(innerVariable);
innerFunction();