(function () { function form2httpAuth () { /* Skip if the browser indicates it does this itself. */ if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("HTTPFormAuth", "1.0")) return true; /* Attempt login with provided credentials. */ var username = this.username.value; var password = this.password.value; var authed = false; var form = this; $.ajax({ url: "/ajax-login.php", /* synchronous hangs some browsers temporarily. :/ */ async: false, global: false, username: username, password: password, dataType: 'text', success: function (data, status, xhr) { authed = true; }, error: function (xhr, status, err) { authed = false; }, complete: function (xhr, status) { /* Don't send username and password if we successfully managed to auth via HTTP */ if (authed) { form.username.parentNode.removeChild(form.username); form.password.parentNode.removeChild(form.password); } } }); /* This is the only way to get browsers to submit the form exactly as the user did, which is why we aren't using async above. */ return true; } $("form.http-authentication").submit(form2httpAuth); })();