-1

I have an asynchronous jsonp-Call and try to assign the result to the variable "FILL_ME" in the example below.

The onSuccess function is called successful, nevertheless it is not possible to assign it's value to the variable "FILL_ME". Instead the error is thrown: Uncaught TypeError: Cannot read property '0' of undefined, which seems like a scope issue.

Please have a look at the following code.

The console.log("final " +FILL_ME) is triggered before the onSuccess method.

How would I assign the result to a variable?

function foo() {
  var FILL_ME = 'OVERWRITE ME';
  var $jsonp = (function() {
    var that = {};
    that.send = function(src, options) {
      var callback_name = options.callbackName || 'jsonCallback',
        on_success = options.onSuccess || function() {},
        on_timeout = options.onTimeout || function() {},
        timeout = options.timeout || 10; // sec
      var timeout_trigger = window.setTimeout(function() {
        window[callback_name] = function() {};
        on_timeout();
      }, timeout * 1000);
      window[callback_name] = function(data) {
        window.clearTimeout(timeout_trigger);
        on_success(data);
      }
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src = src;

      document.getElementsByTagName('head')[0].appendChild(script);
    }
    return that;
  })();

  $jsonp.send('https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json', {
    callbackName: 'jsonCallback',
    onSuccess: function(json) {
      console.log('onSuccess!' +json);
      FILL_ME = json["sites"][0]["siteName"];
      console.log(FILL_ME);
    },
    onTimeout: function() {
      console.log('onTimeout!');
      FILL_ME = '';
      console.log(FILL_ME);
    },
    timeout: 5
  });
  console.log("final " +FILL_ME)
}
<body onLoad="foo()">

</body>
James Z
  • 12,209
  • 10
  • 24
  • 44
AppRoyale
  • 403
  • 1
  • 5
  • 21
  • Well the error is saying that `json["sites "]` is undefined so I would look to see why that is the case. – epascarello Nov 01 '17 at 14:43
  • Thank you. I fixed it. Problem still exists. – AppRoyale Nov 01 '17 at 14:49
  • 1
    Duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – JJJ Nov 01 '17 at 14:56

1 Answers1

2

Cannot read property '0' of undefined

is referring to where you try to access the data returned from your jsonp call, specifically where you try to access property 0 of the array:

json["sites "][0]["siteName"];

That means that json["sites "] is undefined. Likely because of the extra space after sites. It seems to work correctly if you remove that space:

http://plnkr.co/edit/UpGMxruppHeh1U8x0j7B

If you want to use the variable outside of your onSuccess callback, you'll have to write another method you call and pass in FILL_ME like so:

function runAfterSuccess(p_FILL_ME) {
  console.log("Here I can do whatever I want with FILL_ME", p_FILL_ME);
}

Then in your onSuccess callback use:

runAfterSuccess(FILL_ME);

Ben
  • 5,079
  • 2
  • 20
  • 26
  • Thank you for the answer. That is true. Nevertheless, the problem is from different nature. When you have a look at the bottom of the page and check the final console.log. => console.log("final " +FILL_ME) <= you will notice that this code is triggered before the onSuccess method. How would I assign the result of the onSuccess method to a variable though? – AppRoyale Nov 01 '17 at 14:51
  • 1
    In your code you're calling `console.log("final " +FILL_ME)` outside of the callback so of course it's running before being overwritten. The `console.log(FILL_ME);` from inside the onSuccess callback is working as you intended, that's why `SitePoint` is showing in the console. – Ben Nov 01 '17 at 14:56
  • @AppRoyale updated answer & plunkr to address your original question. – Ben Nov 01 '17 at 15:01