1

I am a newbie to Jquery. I am trying to send a request with basic authentication using jquery. This is what i do.

$.ajax({
          type: "GET",
          url: domain,
          dataType: 'json',
          success: function(){
            alert('Thanks for your comment!'); 
          },
          error:function(){
            alert('here');
          },
          beforeSend: function(xhr){ 
            xhr.setRequestHeader('Authorization', 'Basic ' + encodeBase64(username + ":" + password));
          }
});

But my problem is I dont get any feedack. Looks like both the success or the error method is called.

On further debugging i get

Uncaught ReferenceError: encodeBase64 is not defined

What am i missing? Help would be appreciated.

Neelesh
  • 3,673
  • 8
  • 47
  • 78

1 Answers1

7

The error is saying that there is no method called encodeBase64 defined.

Many browsers have a built-in conversion from ascii to base64 called btoa:

xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));

If you are supporting older browsers, make sure that there is a base64 polyfill, such as the one at http://ww.w.icodesnip.com/search/javascript%20dark%20codes/45

steveukx
  • 4,370
  • 19
  • 27
  • thanks that helped. But when I deliberately change to a wrong username/password I find the error method is never called. – Neelesh Feb 21 '12 at 15:07
  • Does your server respond with a 401 status code when the username/password are wrong? – steveukx Feb 21 '12 at 17:56
  • Yes it returns { "error": { "code": 401, "message": "Unauthorized: Basic Authentication Required" } } – Neelesh Feb 22 '12 at 13:14
  • Unless the HTTP status code is a 401, jQuery will be running the success handler instead of the error handler (it sees the XHR as having been successful if there is a 200 HTTP status code). You may find it easier to move your logic to the "complete" handler instead and check the message body of the response to see if there is an error or not. – steveukx Feb 22 '12 at 17:34