Casteurr
Casteurr

Reputation: 956

How to use JSONP

I have the following code

function exista(word) {
    alert(word);
    var exists = 1;
    jQuery.ajax({
        async: false, 
        url: "http://api.wordreference.com/0.8/key/json/roen/" + word,
        dataType: 'json',
        method: "GET",
        success: function(transport) {
            if (transport.Error || transport.Response)
                exists = 0;
        }

    });
    return exists;
}

which verifies if a word exists or not in a dictionary. Problem is it gives an Access-Control-Allow-Origin error. From what I gathered it seems I must use JSONP but I can't really figure out how (sorry, I am just beginning to learn JavaScript and all that). So, got any idea on how to modify the above code?

Thank you.

Upvotes: 2

Views: 2279

Answers (2)

pete
pete

Reputation: 25081

Your dataType should be jsonp, not 'json`.

UPDATE

According to http://www.wordreference.com/docs/api.aspx:

Additionally, for JSPONp, the JSON API can take an optional callback function in the query string; simply add "?callback={yourCallback}" to the end of the URL.

so the API does support JSONP.

Additionally, JSONP means "JSON with padding", so you will get a JSON response. JSONP merely allows use of CORS.

By changing your dataType to jsonp:

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

You can override the default callback by specifying one with the jsonpCallback setting.

Finally, you should also add an error handler and set async to true:

jQuery.ajax({
    "async": true, //cannot be false for JSONP
    "url": "http://api.wordreference.com/0.8/key/json/roen/" + word,
    "dataType": 'jsonp',
    "method": "GET",
    "error": function (jqXHR, textStatus, errorThrown) {
        //included so you can see any errors
        console.log(textStatus + ': ' + errorThrown);
    },
    "success": function (data, textStatus, jqXHR) {
        //According to API documentation
        //data will not likely contain either Error, or Response
        //so, exists will likely not change to 0
        if (data.Error || data.Response) {
            exists = 0;
        }
    }
});

UPDATE:

The solution to both the error and the "need to be synchronous" is going to be what Pointy pointed out earlier. You'll have to create a server-side proxy that runs on the same domain as your script.

The server-side proxy can return JSONP, but frankly simply returning JSON or XML is simpler since CORS is not an issue, and the proxy can be synchronous. For a PHP example script, the Yahoo! Developer Network hosts source code for a simple proxy.

For anything else regarding a server-side web service proxy, you'd need to specify which server language you're using (and it would probably be better suited as a different question).

Upvotes: 3

Pointy
Pointy

Reputation: 413702

For JSONP to work, you not only have to code for it on your side, but the site you're targeting has to expect to be used that way as well, and respond to requests accordingly.

If the other site does not have a JSONP API already, and you have no control over it, then JSONP is not an answer. You'll have to create a server-side proxy of your own.

edit — according to the site, they do support JSONP. You just need to add "?callback=?" to the end of the URL.

Upvotes: 0

Related Questions