4

I have a Django site and I am trying to set a cookie in a response from an AJAX call. I made the question more general since nowbody was answering Cookies not working with an AJAX call from jQuery to Django

On the client side I have a JavaScript function sending a GET request to a URL:

$.ajax({
    url: url,
    success: function(data) {
        alert('Load was performed.');
    }
});

On the server side I have code setting the cookie:

def vote(request, slug, rating):

    # Some irrelevant code...
    response = HttpResponse('Vote changed.')
    response.set_cookie('vote', 123456)
    return response

I get the response in the jQuery code, but the problem is that the cookie is never set in the browser.

What I am doing wrong?

Thanks!

Community
  • 1
  • 1
Alex Gonzalez
  • 981
  • 1
  • 11
  • 17

1 Answers1

3

Try creating the cookie specifying an expiry date, something like the below:

var max_age = 14*24*60*60 # two weeks
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")

response.set_cookie('vote', 123456, max_age=max_age, expires=expires)

Apologies if the example is a little off - it's been a while since I worked with Django and had to google the cookie/date syntax.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339