0

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

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Pedro Antônio
  • 395
  • 1
  • 6
  • 19

2 Answers2

3

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();
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Just define Hi() outside the onDeviceReady() function.

document.addEventListener("deviceready", onDeviceReady, false);
function Hi(img_url){
  alert('Hi, the img_url is '+img_url);
}
function onDeviceReady() {
  alert('device ready');

}

In javascript you can't use a function outside the scope it was defined. Here is a detailed description of scope in JS: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
jetpackpony
  • 1,270
  • 1
  • 12
  • 22