AP257
AP257

Reputation: 93813

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!

Upvotes: 16

Views: 14855

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

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);
});

Upvotes: 29

Related Questions