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) { alert("error"); return; } alert(xml.responseText); }; xml.send(null);
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
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.
LikeLike
@russell because of the same origin policy restriction in browsers. Look at http://www.w3.org/TR/cors/ to get around this.
LikeLike
thanks for the snippet… Funny how the image is really from a brand of cleaning products
LikeLike
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
Cheers
LikeLike
Credentials aren’t passed with the open method. Credetials are passed only if the server request them with a return code 401.
LikeLike
It’s hard to find knowledgeable people on this topic, however, you sound like you know what you’re talking about!
Thanks
LikeLike
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
LikeLike