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.

5
  • Have you looked in the console if there are any errors or with firebug what the response to your post is ? Commented Feb 21, 2012 at 14:40
  • updated my question with console output Commented Feb 21, 2012 at 14:42
  • then you have your error the function encodebase64 is undefined Commented Feb 21, 2012 at 14:43
  • android/iOS ? or do u see this error while testing on browser? Commented Feb 21, 2012 at 14:44
  • This is your answer stackoverflow.com/questions/246801/… Commented Feb 21, 2012 at 14:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks that helped. But when I deliberately change to a wrong username/password I find the error method is never called.
Does your server respond with a 401 status code when the username/password are wrong?
Yes it returns { "error": { "code": 401, "message": "Unauthorized: Basic Authentication Required" } }
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.