jQuery Ajax Unauthorized 401 Error

6.4k views Asked by At

I have this code:

<?php
$username = $_POST['username'];
$password = $_POST['password'];
$ck = time();
$read = new GoogleReaderAPI( $username, $password );
$token = $read->getToken();

echo "RSS Feed: <input type='text' name='rss_feed' /> <br /> ";
echo "<input type='hidden' value='$token' id='token' />";
echo "<input type='hidden' value='$ck' id='ck' />";
echo "<input type='hidden' value='$username' id='username' />";
echo "<input type='hidden' value='$password' id='password' />";
echo '<input type="button" value="Submit" id="click"/>';
echo "<div id='result'></div>";
?>
<script>
jQuery("#click").click(function(){
    var quickadd = escape( jQuery("input[name=rss_feed]").val() );
    var T = escape( jQuery("#token").val() );
    var ck = escape( jQuery("#ck").val() );
    var params = "quickadd="+quickadd+"&T="+T;

        jQuery.ajax({
            type: "POST",
            url: "http://www.google.com/reader/api/0/subscription/quickadd?ck="+ck+"&client=scroll",
            data: params,
            contentType: "application/json",
            success: function(data){
                alert(data);
            }
        });
    });

I'm getting a 401 Unauthorized error when using ajax but when I try to use an ordinary POST method (non-ajax), then I am able to see the output.
This is an exmaple ouput that i'm seeing when using an ordinary POST

{"query":"http://feeds.feedburner.com/TechCrunchIT","numResults":1,"streamId":"feed/http://feeds.feedburner.com/TechCrunchIT"}

By the way i'm integrating the google reader account in my application that is why i'm calling that one in the ajax-url.

1

There are 1 answers

6
Ramil Amerzyanov On

This should help you

jQuery.ajax({
            type: "POST",
            url: "http://www.google.com/reader/api/0/subscription/quickadd?ck="+ck+"&client=scroll",
            data: params,
            contentType: "application/json",
            beforeSend: function(xhr) {
                 xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password) //May need to use "Authorization" instead
            },
            success: function(data){
                alert(data);
            }
        });