Pedro Antônio Pedro Antônio - 4 years ago 183
Ajax Question

Function inside Ajax success - Cordova/Framework7

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);
}
}


The ajax request:

$$.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);
}
});


But the function
Hi()
is always'undefined'...What's wrong?

Thanks

Answer Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download