Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Django session variable in javascript?

I want to update a Django session variable following a Javascript event (well, actually jQuery).

Do I need to do this via a POST request?

Or can Javascript and Django share session variables in some clever way, in which case can I update the session variables direct from jQuery? I'm a bit hazy on the details.

Thanks!

like image 370
AP257 Avatar asked Jan 04 '11 16:01

AP257


1 Answers

You can do this via Ajax. You'll need a simple Django view that updates the session variable, which the jQuery will call:

def update_session(request):
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])

    request.session['mykey'] = 'myvalue'
    return HttpResponse('ok')

and the JS:

$.post('/update_session/', function(data) {
    alert(data);
});
like image 137
Daniel Roseman Avatar answered Nov 16 '22 08:11

Daniel Roseman