3

So I already have the website working (I'm not working from scratch). The problem I have is that a lot of the content is available only if you're logged in (pretty much everything). So sometimes I have a modal popup which retrieved (using ajax) something to display.

In my server side code, if someone's not logged in, they are redirected to the sign-in page.

This produces a strange effect, as if someone is on a page and is no longer logged in, then the modal that pops up tries to display the sign in page.

What possibilities are there for straightening this out?

The only thing I can think of is having a url that checks if they're logged in and returns that, and along with every ajax request, I could check if they're logged in or not and the Javascript could act accordingly.

I'm hoping there's some other possibilities.

1 Answer 1

5

I've solved it like this.

  1. On server side, process authentication error differently depending on whether request is ajax or not. In first case - return 401 'unauthenticated' response, in second - redirect to sign-in page.
  2. On client side, register common jquery ajax error handler to catch 401 errors and redirect user to login page.

    $.ajaxSetup({
        error: function(event, request, options, error) {
            switch (event.status) {
                case 401: common.setLocation('/sign-in'); break;
                ...
            }
        }
    });
    

It's quite simple solution, you don't even have to modify each particular request, so hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

@Matthew You can check 'X-Requested-With' request header. It's set by jquery on each ajax request. How to do it depends on your language and framework, but it should have some API to process headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.