Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 429
Peter Avatar asked Apr 14 '11 10:04

Peter


2 Answers

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.

like image 118
lonesomeday Avatar answered Oct 05 '22 09:10

lonesomeday


You need to set dataType: "jsonp" and you need to be logged in as the user you are trying to get favorites from. In this case I use my own username grabot and the alert comes back as success.

If you don't have a valid cookie for the account your trying to access then the api call will return a 403 with the content "Favorites of requested user are not public."

$(function() {
    var jqxhr = $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/users/gradbot/favorites?alt=json',
        dataType: 'jsonp'
    }).success(function(data, status) {
        alert(status);
    }).error(function(xhr) {
        alert(xhr.status);
    })
});
like image 31
gradbot Avatar answered Oct 05 '22 10:10

gradbot