Search code examples
jqueryajaxjsonpcors

Can I access any API with JSONP or does the API need to specifically support it?


I am trying to access an API from bar.com from my site foo.com. Bar.com does NOT allow CORS, and I don't know if they officially support JSONP.

Can I still access the API via JSONP (using jQuery) or does the site explicitly need to support it?

Note, this is my AJAX request:

    $.ajax({
        url: 'https://api.example.com',
        jsonp: 'callback',
        dataType: 'jsonp',
        data: {
            'command' : 'abc',
            'partnerName' : 'def',
            'partnerPassword' : 'ghi',
            'partnerUserID' : 'jkl',
            'partnerUserSecret' : 'mnop'
        },
        error: function (response) {
            console.log(response);
            return false;
        },
        success: function (response) {
            console.log(response);
            return false;
        }
    });
},

From Chrome I get:

Uncaught SyntaxError: Unexpected token :

Solution

  • It's because what JSONP does is try to evaluate the code that comes from the API endpoint.

    If the result of the call is, let's say

    {"result": "OK"}
    

    then, to make JSONP work, the server had to respond it in that way:

    callback({"result": "OK"})
    

    as oyu defined a property jsonp as callback in your ajax call.