jqXHR - http-status-code-403 (but the statuscode is 0)

Peter picture Peter · Apr 14, 2011 · Viewed 14.9k times · Source

i get the statuscode 0 ... but it is the code 403. Can someone tell me what the problem is?

JQUERY

  var jqxhr = $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/users/bernd/favorites?alt=json',
        dataType: 'json'
    }).success(function(xhr) {
        alert(xhr.status);
    }).error(function(xhr) {
        alert(xhr.status);
        return false;
    })

DEMO -> http://jsfiddle.net/QFuBr/

Thanks in advance!
Peter

Answer

lonesomeday picture lonesomeday · Apr 16, 2011

The server gives a 403 error to a browser, because you don't have permission to access the resource, because of the error message reported ("Favorites of requested user are not public.").

However, the server doesn't even get the request in the jsFiddle example.

You aren't allowed to make cross-browser AJAX requests. This is called the same-origin policy. It is for security reasons, to prevent malicious coders from doing unpleasant things without your knowledge. It's a blunt tool, but an effective one.

When you don't even get as far as sending a request to the server, there is no status code. This gets reported by the XMLHTTPRequest object (and its jqXHR wrapper) as 0.

Basically, you can't do what you're trying to do in the browser.

If you need the browser to access data like this asynchronously, you'll need to write a wrapper on your server to fetch the information from the remote server and feed it to the browser. There is a workaround (it's called JSONP – JSON with Padding) but I don't believe YouTube supports it.


Edit: Per gradbot's answer, it is possible to do a JSONP request by changing your code to set dataType to jsonp.

However, you won't now be able to use xhr.status. This is because JSONP does not use the XHR object, so there is no status available to check.

Here's a working example using the feed gradbot suggested. Note that the result object is passed to the handler, rather than the jqXHR object.