Home > Uncategorized > Basic HTTP Authentication over XMLHttpRequest (AJAX)

Basic HTTP Authentication over XMLHttpRequest (AJAX)

Here is a simple way to perform basic HTTP Authentication with a XMLHttpRequest – Ajax request – from your webpage.

       var url = 'http://someurl.com';
	xml = new XMLHttpRequest();
	xml.open("GET", url, false, "username", "password");
	xml.onreadystatechange = function() {
	   if (xml.readyState != 4)  { return; }
	   if (xml.status != 200)  {

You don’t have to do the Base64 encoding yourself, unlike some examples online. – Do note that “url” needs to be on the same domain as your script.

Categories: Uncategorized
  1. November 2, 2012 at 10:19 am

    Why does the url need to be the same domain as the script? If it weren’t for that this would be exactly what I’m looking for.


  2. July 11, 2013 at 8:11 am

    @russell because of the same origin policy restriction in browsers. Look at http://www.w3.org/TR/cors/ to get around this.


  3. Porjolovsky
    May 27, 2014 at 1:50 pm

    thanks for the snippet… Funny how the image is really from a brand of cleaning products


  4. Porjolovsky
    May 27, 2014 at 2:41 pm

    Still, why are you setting the open method to synchronous? Check out the MDN docs where it states that the onreadystatechange method should not be used while performing synchronous requests: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties



  5. Samir
    September 1, 2014 at 8:33 am

    Credentials aren’t passed with the open method. Credetials are passed only if the server request them with a return code 401.


  6. September 23, 2014 at 8:49 pm

    It’s hard to find knowledgeable people on this topic, however, you sound like you know what you’re talking about!


  7. biggie4life
    October 22, 2015 at 6:23 pm

    Nice code exampe @dananos, thanks. You might be interested in how to use HTTP Basic Auth with raw javascript XmlHttpRequest interface. See http://zinoui.com/blog/ajax-basic-authentication


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: