0

im trying to understand callbacks and get a result (i grab jsonP data via cross-site). It works but it did not work if i wrap it in function. I think the function returns before the request is ready. But i already stuck in callback function?! It seems i understanding something wrong.

Can you guys help me out please?

In head i got this request function:

function checkThis(){   

        var s = document.createElement("script"),
        callback = "...",
        url = "https://...?callback=" + callback;
        window[callback] = function (data) {            

            return data.valid;

        };
        s.src = url;
        document.body.appendChild(s);       

    }

And it is basically working good.

But when i try to load it in body section with:

alert( checkThis() );

It return undefined, i know cos its not ready?! But how to solve. I try to understand the basics!

Is setInterval() a solution?

Thx guys!

  • 2
    `checkThis` has no return value, hence you wont see anything in `alert`. – rajuGT Nov 13 '15 at 08:18
  • Just a pointer, using global variable is not a good practice. – Rajesh Nov 13 '15 at 08:21
  • I need this function in global space. Or what you mean? And for the first hint: i got a return in the callback?! If i change to alert in the callback and execute driectly its working....(maybe retunr empty but no undefined). I need this function in global space (e.g. not in a docs ready for example) –  Nov 13 '15 at 08:24
  • @Rajesh: Just a pointer, global variables are a necessity for JSONP. – Bergi Nov 13 '15 at 08:54
  • @Bergi sorry, but I dont have knowledge about JSONP and cannot comment about it. Also can we not use `callback`? [Might be helpful](http://stackoverflow.com/questions/7613815/callback-function-for-jsonp-with-jquery-ajax) – Rajesh Nov 13 '15 at 09:11

0 Answers0