Cannot get cookie value - javascript

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

Related

How do I store if a user clicked a button on a cookie using JavaScript?

I'm trying to make a simple website for a friend. The purpose is picking a ticket and showing an alert and disabling the button showing that the ticket has been already redeemed. I also want to store that on a cookie, because if my friend leaves the webpage, the values are restored to default and not based on the choices my friend have made.
The HTML code is this:
<img id="first_ticket" src="ticket_not_edited.png" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="first()">Redeem</button>
The JavaScript code is:
function first() {
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background='#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src='broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
The purpose is to store the user's choice on a cookie so I can always check what my friend has chosen to disable the ticket and the button availability.
Also, how can I make it to check if my friend chose a ticket to disable some options (by "some options" I'm referring to disabling the button and changing the image to a broken ticket"?
Thanks in advance!
You can use document. cookie to store the answer, and you can check in the link below to know if it exists.
Got it from here:
final:
<img id="first_ticket" src="" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="checkIfExists()">Canjear</button>
<script>
// check if it Exists
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
var myCookie = getCookie("first");
if (myCookie == null) {
alert('Welcome! Please Choose A ticket below.');
}
else {
alert('Welcome back! You already choose a ticket!');
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
function checkIfExists() {
if (myCookie == null) {
document.cookie = "first = 'yes'";
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
else {
alert('Oh. You already choose a ticket.');
}
}
</script>

How to set a check if coupon code used one time then do not allow to use it second time in one transection

This is my code
html input field
<input type="text" size = "3" name="couponadd" id="couponadd"
oninput="myFunction()" class="field" placeholder="Enter Coupon Code" />
Script Code
<script>
var lastval;
function myFunction() {
getting CouponDC,TicketypDC and CouponPrcDC from database
var CouponDC = $('#dbcoupan').val();
var TicketypDC = $('#dbtckettype').val();
var CouponPrcDC = $('#dbprice').val();
var total_price = $('#total_price').val();
Get getcoupon from input
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
check if user enter same coupon
if(getcoupon == lastval )
{
alert('You Cant Enter Same Code Again');
}
if coupon code match with database coupon
else if (getcoupon == CouponDC ) {
$amount=CouponPrcDC;
total_price = total_price * ((100-$amount) / 100);
minus some ammout from total if match
total_price = Math.round(total_price);
document.getElementById('Voucher_value').value = total_price;
}
if coupo don't match with database coupon
else if(getcoupon != CouponDC && getcoupon.length ==5 )
{
alert('WRONG COUPON CODE');
}
**store last value enter in input**
lastval = getcoupon;
$('#total_price').val(total_price);
}
</script>
You can store it in an array and check if it exists before moving ahead.
Pseudo code below:
var couponArr = [];
var getcoupon = $("#couponadd").val();
if($.inArray(getcoupon, couponArr) !== -1) {
alert('Coupon already used, can\'t use again.');
} else {
couponArr.push(getcoupon);
// your code here..
}
inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
Add a global tag variable and set default to false,use a if condition wrap the code need to run,then in the run code set it to true.
such as:
// in outer space
var hasCodeRun = false;
// in some function
if (!hasCodeRun) {
// run code here
hasCodeRun = true;
}

Keep form data with back button

there are many questions similar to this but none of them seem to help with my situation.
I am developing a three step process using Javascript and html
I have 2 forms in the first two steps.each with a next/prev button
I need to be able to go back from step two back to step 1 and still have step ones form data in the fields. I am rather new to javascript any help would be appreciated. I am unsure how to save the form data and then insert it when the user goes back from step 2
EDIT:
I have decided to use JS to hide/show forms, please can someone tell me why my variable never gets to currentStep == 3; this causes issues when going back as it goes back to step one becasue the currentStep value is stuck at 2
var currentStep = 1;
function nextStep() {
if (currentStep ===1){
$("#petmain1").hide();
$("#petmain2").show();
$("#addproduct").show();
$("#firstimage").hide();
$("#secondimage").show();
currentStep = 2;
console.log("Current step is " + currentStep);
}else if(currentStep ===2){
$("#petmain2").hide();
$("#addproduct").hide();
$("#secondimage").hide();
$("#petmain3").show();
$("#thirdimage").show();
$("#firstimage").hide();
currentStep === 3;
console.log("Current step is " + currentStep);
}
}
function prevStep() {
if (currentStep ===2){
$("#petmain1").show();
$("#petmain2").hide();
$("#addproduct").hide();
$("#firstimage").show();
$("#secondimage").hide();
currentStep = 1;
console.log("Current step is " + currentStep);
}else if(currentStep === 3){
$("#petmain3").hide();
$("#thirdimage").hide();
$("#secondimage").show();
$("#petmain2").show();
$("#addproduct").show();
currentStep === 2;
console.log("Current step is " + currentStep);
}
}
You can use localStorage
On navigating from first step to second step you can store the value
if(typeof(Storage) !== "undefined") {
localStorage.setItem("someKey", $("#somField").val());
} else {
//
}
Again on navigating from second to first step check the local storage for the value and assign it to the fields in first form
$("#somField").val(localStorage.getItem("someKey"))
You may use sessionStorage.
HTML
<form>
Username : <input type='text' id='name'> <br />
Password : <input type='password' id='password'> <br />
<input type='button' onclick='storedata()' value='submit'>
</form>
<p id='res'></p>
JS
window.onload = function() {
if (sessionStorage.name && sessionStorage.password) {
document.getElementById("name").value = sessionStorage.name;
document.getElementById("password").value = sessionStorage.password;
}
};
function storedata() {
if(typeof(Storage) !== "undefined") {
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
sessionStorage.name = name;
sessionStorage.password = password;
document.getElementById("res").innerHTML = "Your datas restored";
} else {
document.getElementById("res").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Working Demo : https://jsfiddle.net/d83ohf6L/

how to add one error instead of multiple errors

Hi I have designed my form now i am unsure how to combine all the alert messages instead of them popping up one at a time , please could someone tell my how to do this in simple terms as i am new to javascript. thankyou in advance. below is my script.
function validateForm() {
// this part of the script will collate all errors into one should the user leave an input blank
var Fname=document.forms["myForm"]["fname"].value;
var Lname=document.forms["myForm"]["lname"].value;
var address=document.forms["myForm"]["addr1"].value;
var postcode=document.forms["myForm"]["pcode"].value;
var email=document.forms["myForm"]["email"].value;
var number=document.forms["myForm"]["tel"].value;
var date=document.forms["myForm"]["mydate"].value;
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date)
{
alert("Please make sure all fields are filled or checked correctly out ");
return false;
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode))
{
alert("That Post Code is incorrect, correct way mk4 4tr");
return false;
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail))
{
alert("That email is incorrect");
return false;
}
// end of email script
// start of phone number script
var phonestring = /^(?:0|\+44)[12378]\d{8,9}$/;
if (!number.match(phonestring))
{
alert(" incorrect,correct format 01908234874");
return false;
}
// end of phone script
//start of gender script
if ( ( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
// end of gender script
//start of age group script
if((myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )){
alert("please select an age group");
return false;
}
// end of age script
//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;
if (!date.match(dateformat))
{
alert("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
return false;
}
var today = new Date();
var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits
var courseDay = date.substr(0,2)//e the first and second digits
var dateToCompare = new Date(courseYear, courseMonth, courseDay);
if (dateToCompare < today) {
alert("this date is in the past");
return false; }
//end of date field
else
{ alert(" Thank you a member of our team will get back to you shortly");
return true;}
}
create some kind of collection that you can append to and instead of alerting independantly, just add them to the set. Something like:
function validateForm(){
var errors = []; // new array to hold all the errors
/*
validation code that instead of
alert('error')
use
errors.push('error');
Also remove any premature `return` statements and
leave them until the end.
*/
// next check if there are errors
if (errors.length > 0){
// display them
alert('Following errors found:\n- ' + errors.join('\n- '));
// also return false to flag there was a problem
return false;
}
// if we reached this code there were no errors
return true;
}
Add all your errors to an array and then alert them at the end, if any exist:
function validateForm() {
var errors = []; //array for holding errors
.
.
.
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date) {
errors.push("Please make sure all fields are filled or checked correctly out "); //add error
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode)) {
errors.push("That Post Code is incorrect, correct way mk4 4tr"); //add error
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail)) {
errors.push("That email is incorrect"); //add error
}
if(errors.length > 0) {
alert('The following errors occurred: ' + errors.join('\n')); //alert errors if they exist
return false;
}
return true; // allow submit
}

Dynamic form validation with ASP variables

I have 52 members in my database. When displayed in the admin panel, each one has a form associated with it so I can make notes for each member.
Each Member has an ID so I name each form on the page like this: "frmRepNotes<%=MemberList("MemberID")%>" based on the memberID from the database. This results in something like frmRepNotes67453. I now want to validate the form before saving the notes.
How can I use that number in the JavaScript?
function validate(strid)
{
var ErrorFound = 0
if (document.'+strid+'.taNotes.value == '')
{
ErrorFound = ErrorFound + 1
}
if (ErrorFound == 0)
{
document.'+strid+'.submit();
}
}
How can this be done?
Consider refactoring to be something like this?
function validate(strid)
{
var ErrorFound = 0;
var theForm = document.getElementById("frmRepNotes"+strid);
if (theForm.taNotes.value == '')
{
ErrorFound +=1;
}
if (ErrorFound == 0)
{
theForm.submit();
}
}

Categories