I need to check that the user is still logged in so that I can prevent them from even opening the form if their session expired (logged out but page hasn’t been refreshed).
Here’s the pseudo code of what I was trying to do, doesn’t work obviously.
// some view.html
$('#someform').click(function() {
ajax(URL('login_status'), [], '');
});
// some controller.py
def login_status():
if not auth.user:
redirect('index')
If you want the full page to redirect as the result of an Ajax request, you’ll have to do it via Javascript on the client rather than via a server-side redirect (which will only redirect the Ajax request itself). To make that happen, you can specify “:eval” as the target in the
ajax()function, which will result in the returned response being executed as Javascript code (see here). So, something like:So, the Ajax call returns Javascript that either shows the form or redirects the page, depending on whether the user is logged in.
Also, note that the
URL()function is a server-side Python function, so you can’t just call it within theajax()function, which is a client-side Javascript function. Instead, you have to put it inside web2py’s template delimiters ({{ }}) so the URL will be generated in the template on the server.UPDATE: Instead of:
you can now do:
which will do the same thing behind the scenes.