If you are pulling your hair out while trying to demo a JSONP call with JSFiddle, don’t bother. It won’t work out of the box.
There is no doubt that JSFiddle is a super-useful tool for saving little demos that you can share with others. I use it like crazy when providing simple demos in this blog. Tons of cool features and in general, a brilliant idea.
One little quirk I ran into this morning is JSONP calls. I’m writing Part II of a post called: “Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object”. In this second part, I introduce the tricky scenario of adding a JSONP call as a dependency, which is in addition to other dependencies that are multiple asynchronous JavaScript calls that may (or may not) have already loaded in the page (I know, I know….. I need to get a life).
Anyhooooo….
When attempting the code in example # 1, I got the following error: “myCallback is not defined”.
Example # 1
1 2 3 4 5 6 7 8 9 |
var myCallback = function(data){ console.dir(data); }, script = document.createElement('script'); script.src = 'http://examples.kevinchisholm.com/utils/json/jsonp.php?callback=myCallback'; document.getElementsByTagName('head')[0].appendChild(script); |
My guess is that JSFiddle uses iframes to render your test code. I’ve not made any attempt to look into this further, and I’m sure the answer is likely a call to “parent” or something similar. But just in you are pulling your hair out trying to demo a JSONP call using JSFiddle, hopefully this will save you the 20 minutes of troubleshooting that I just did. It won’t work out of the box (again, probably due to the use of iFrames). When I figure out the answer, I will post it. I’ll try to look into it this weekend.
Kevin
Check out codepen.io. It uses iframes too, but when I put your code into a codepen example, I did not see your error. The console reports getting the array.
I have seen other weird quirks that JSFiddle can’t seem to handle, but I can’t remember them off the top of my head at the moment.
Hey thanks a lot Stephen. I’ve messed around with codepen.io a little bit and was impressed, but maybe I should consider using that for my blog’s code examples…. I will definitely re-visit.
Kevin
[…] Last week I published this post: Problems Making JSONP Calls in JSFiddle […]