Search code examples
javascriptjqueryhtmlajaxhttp-authentication

Avoid Login popups when JQuery loads content with $.ajax


I have a index.html which loads 3 blocks of content using 3 different $.load(...) queries. When I use basic http authentication , the login and pass is requested 4 times. 1 on the page load, and 1 for each content.

How can I keep the login up, WITHOUT passing it on the $.load url? (for security purpose).

    <div id="header"></div>
    <div id="maindiv"></div>
    <div id="footer"></div>

    <script type="text/javascript">
    $(document).ready(function() {
        $("#header").load("?cmd=header");
        $("#maindiv").load("?cmd=viewconfig");
        $("#footer").load("?cmd=footer");
    });
    </script>

Solution

  • You should modify the response to a 401 http status code instead of the Authorization http header. Then you can catch these responses and show your own login dialog popup.

    In my example, all JQuery Ajax call result statuses are checked for the 401 code and the first occurrence will show the dialog:

    var loginFormShown = false;
    $.ajaxSetup({
      statusCode: {
        401: function(xhr) {
          if(!loginFormShown) {
            console.log('Show login form popup', xhr.responseText);
            loginFormShown = true;
          }
        }
      }
    });
    $(document).ready(function() {
        $("#header").load("?cmd=header");
        $("#maindiv").load("?cmd=viewconfig");
        $("#footer").load("?cmd=footer");
    });