1

I have a jQuery AJAX call that works perfectly well:

$.ajax({
    url: "http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre",
    dataType: 'jsonp',
    success: function(data){
        filter(data); // Callback function
    }
});

However I cannot get a pure JS version of this to work, the dataType: jsonp is giving me trouble. My attempts are as follows

This approach gives me an error of Unexpected token :, adding ?callback=filter to the end of the URL says the page is not found

var script = document.createElement('script');
script.src = 'http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre';
console.log(script);
document.body.appendChild(script);

My second approach; Gives me an error of Unexpected token : as well

function jsonp(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
}    
function jsonpCallback(data) {
     filter(JSON.stringify(data));
}    
jsonpCallback(jsonp("http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre"));

My third approach; Gives me an error of cannot load (the url). Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre", true);

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            filter(JSON.stringify(data));
            console.log(JSON.stringify(data));
        }
    }       
    xmlhttp.send();
}
loadXMLDoc();

Here is the jsFiddle

Where am I going wrong?

4
  • Are you building this in jsfiddle? Possible to see the link? Commented Oct 15, 2013 at 23:24
  • Yes, I am building in the jsFiddle. I added the link in the question Commented Oct 15, 2013 at 23:24
  • @Zeaklous jsfiddle.net/FSyT5/1, I will also check how you can fix it with jQuery ;) Commented Oct 15, 2013 at 23:34
  • @plalx I don't need a jQuery fix, I already have one that I provided in the question. And when I try to implement your fix on the full jsFiddle I get an error of An attempt was made to reference a Node in a context where it does not exist. Commented Oct 15, 2013 at 23:39

2 Answers 2

2

Have a look here jsfiddle.net/FSyT5/1

var script = document.createElement('script');

script.src = 'http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts?api_key=Srhk9qkcJO69pAoB4ltM5uIqpwUBO7kgDqDEaCD9Jo8EafWyHE&callback=filter';

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

window.filter = function filter(data) {
    console.log(data);
};

EDIT:

It seems to work in your simplified version but not in the full jsFiddle, I get an error of An attempt was made to reference a Node in a context where it does not exist. Any idea why?

It's because you cannot do document.body.appendChild("<div id='fromTumblr'></div>");

You have to create your DOM elements like:

var div = document.createElement('div');

EDIT2:

it's not finding any of the object's types even though they are found in the same place in the Object in the console.

Unlike jQuery's each, the first parameter passed to the forEach callback is the item, not the index. The index is the second param, they have inversed APIs.

Sign up to request clarification or add additional context in comments.

6 Comments

It seems to work in your simplified version but not in the full jsFiddle, I get an error of An attempt was made to reference a Node in a context where it does not exist. Any idea why? jsFiddle to show
@Zeaklous Let me check.
@plalx: you might want to define window.filter before appending the <script> tag to <head>, just in case the JSON-P response comes back phenomenally fast.
@PaulD.Waite The current JS block will always execute to the end before the code loaded by the script runs since the script is loaded asynchronously. However it might help readability and comprehension to have it before.
@plalx Again good catch on the error, but now it's saying the object's types are undefined even though they are found in the same place in the Object in the console. Any ideas? I promise this is the last problem, haha
|
0

Have you tried loading the JSONP URL in a browser, and seeing if the JavaScript it returns is valid? I suspect the error may be coming from that JavaScript, rather than what you’ve written.

However, in your second approach, you shouldn’t call jsonpCallbackyourself. The script loaded by your jsonp function will do that.

Your third approach won’t work because you can’t use xmlhttp.open for URLs on a different domain to the script (unless the different domain supports cross-origin resource sharing). The whole idea of JSON-P is to add a <script> tag to the page pointing at a different domain to enable cross-domain requests.

Edit:

Ah, spotted it. I think you literally appended ?callback=filter to the end of the URL you’re using. You want to append a callback parameter to the end of the URL (so that Tumblr returns a valid JavaScript response, as opposed to a JSON response).

As your URL already contains the api_key parameter, you should add &callback=filterto the end of the URL (note the & instead of the ?).

1 Comment

Like I said the jQuery version works just fine, so does opening the JSONP URL in a browser. And thanks for the information on the third approach, I didn't figure it'd work when I tried it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.