1

Trying to access an external API.

Using jQuery 1.9.1.

    $.ajax({
        cache: true, // remove the _ query parameter from the url
        dataType: 'script', // used to be 'jsonp', however changed to 'script' in order to remove the _ query parameter being added to the url
        jsonp: false, // remove the callback query parameter, this causes the url to fail
        type: 'GET',
        url: 'http://api.external-domain.com/format/json/',

        success: function(data){
            alert('success');

            $.each(data.parent, function(i, item){  
                var vname = item.Name;
                $('<li />').html(vname).appendTo('#list');
            });

        },

        error: function(){
            alert('failure');
        }

    });

The success alert is displayed, the item names are not written to the list, however the browsers developer tool states

Firefox: SyntaxError: invalid label

Chrome: Uncaught SyntraxError: Unexpected token

The error message identifies the json file as the cause, however if I copy the same json file and place it on the local server (while amending the dataType to json) it works.

Please help.

spec
  • 23
  • 5
  • 1
    Cross-domain requests need to be performed using JSONP (and hence, a callback function name), unless the remote server has CORS enabled. But in the case of JSONP, the server also has to accept JSONP requests explicitly. – robertklep Mar 05 '13 at 12:01
  • I expect that `data` is still json-encoded, so try `data = JSON.parse(data);` or `data = eval(data);` – Beetroot-Beetroot Mar 05 '13 at 12:05
  • Robertklep, I don't think the server has CORS enabled. Is there another method I could use to parse this external file – spec Mar 05 '13 at 15:56
  • Thanks @Beetroot-Beetroot, I just tried your suggestion, no luck. – spec Mar 05 '13 at 15:58
  • The cross-domain rules are tricky and I've not committed them to memory. Try reading the [accepted answer here](http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin/3744697#3744697). – Beetroot-Beetroot Mar 05 '13 at 18:46
  • Thanks @Beetroot-Beetroot, if this doesn't work I will have to try some other method. – spec Mar 06 '13 at 08:44
  • If JSON(P) won't work, the next approach to try is to get your own server to act as a proxy. This will involve a double request (client-to-own-server and own-server-to-remote-server, then the reciprocal path for the response), but should at least give you *a* working solution albeit potentially sluggish; you can then work on direct JSON(P) later when time permits. Meanwhile, for the proxy solution (and with slow-changing data), you can always improve performance by caching responses at the server - various approaches exist including writing to database or to file(s). – Beetroot-Beetroot Mar 06 '13 at 13:02

0 Answers0