tags:

views:

40

answers:

2

I am trying to bring up the HTTP authentication box for handling my login. However, I want to communicate to my database through Ajax. But I dont know how to connect the HTTP authentication box with AJAX.

Any Idea, how to do this? Please also include example

+1  A: 

Basic HTML:

<form id="login-form" action="/login.php" method="post">
    <label for="username">Username: </label> 
    <input type="text" name="username" id="username"/><br />

    <label for="Password">Password: </label> 
    <input type="text" name="password" id="password"/><br />

    <input type="submit" value="Login"/>
</form>​

Basic jQuery:

$(document).ready(function() {
    $('#login-form').bind('submit', function (e) {
        var self = $(this);

        // See ajax: http://api.jquery.com/jQuery.post
        // See serialize: http://api.jquery.com/serialize()
        jQuery.post(self.attr('action'), self.serialize(), function () {
            if (response.success) {
                // wooo, logged in
            } else {
                alert("Invalid username or password. Please try again");
            }
        }, 'json');

        e.preventDefault(); //prevent the form being posted 
    });
});​

Basic PHP:

<?php
if ($_POST['username'] == 'Admin' && $_POST['password'] == 'letmein') {
    echo json_encode(array('success' => true));
} else {
    echo json_encode(array('success' => false));
};
?>

A little bit of data validation wouldn't go amiss.

Matt
+1  A: 

(To my surprise) jQuery has built-in support for supplying HTTP auth credentials:

$.ajax({
    url: "http://example.org/",
    username: "NAMENAMENAMENAMENAME",
    password: "PWPWPWPWPWPWPWPWPWPW",
    ...
})

Or you can override the XMLHttpRequest object like in this example: http://dothow.blogspot.com/2009/05/http-basic-authentication-with-jquery.html

mario
it doesnot work
Starx
@asdf2: jQuery 1.4.2 works fine for me with username: and password:
mario