I have a script that calls a prompt when I push a button and gets a number from the user. The number is stored in a cookie. Then that script loads a view that gets the number from the cookie and passes it to a form.
Currently I have the cookie being saved; I can see it in the browser debugger. But when I try to get the cookie in my view it always returns null.
I think the request sends a cookie with a null value before updating the cookie.
JavaScript
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
// $(".on_button").click(function() {
var amount = prompt("Please enter amount of orders" ,"0")
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
document.cookie = "amount=" + amount; //+ ";max-age=60";
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});
View
def add_order(request, meal_slug, meal_restaurant):
print("OK")
amount = get_server_side_cookie(request, 'amount', '1')
print(amount)
//clear_amount_cookie(request)
if amount is not None:
meal = Meal.objects.get(
slug=meal_slug, restaurant_slug=meal_restaurant)
user = UserProfile.objects.get(user=request.user)
order = Order.objects.create(
meal=meal, customer=user, amount=amount, date=datetime.now())
order.save()
//clear_amount_cookie(request)
return redirect('food_cloud:index')
Get cookie function
def get_server_side_cookie(request, cookie, default_val=None):
val = request.COOKIES.get(cookie)
print(val) //This is where I see the null value
try:
int(val)
except (ValueError, TypeError):
val = default_val
print(val + " here")
return val
I solved the problem by implementing the jquery.cookies.js objects Link: https://github.com/carhartl/jquery-cookie
Then I replaced the code for creating the cookie. Apparently JQuery is not good for handling cookies directly
Changed code
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
var amount = prompt("Please enter amount of orders" ,"0");
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
Cookies.set('amount', amount) //This is the new code for creating cookie
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.