Obtain the cookie and store it in a variable (with a 24-hour expiration) before transferring it to

I am in need of a unique variable that is valid for a single day. This variable should be able to identify the individual website user and remain exclusive to that user. Once obtained, I intend to store this variable in a MySQL column. However, I am facing challenges in creating such a variable.

Additionally, I require a validation process to check if the record already exists in the table, preventing the creation of a new one within 24 hours.

To achieve this, my initial thought was to use a cookie that expires after one day (although I am not very familiar with cookies). Currently, I am having difficulty figuring out how to alert the cookie as shown below:

$(document).ready(function() {

    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
            }
        }
        return "";
    }   

// Inline Button in Table

var cookie_variable = $('#table').on('click', 'a.cookie_button', function () {

    alert(document.cookie);

} );

});

Alert Result:

[object Object]=[object Object]; cookieconsent_dismissed=yes

Answer №1

It seems like there might be some confusion about what you're trying to achieve or where you're facing challenges, but I have made updates to your code that should resolve the issue.

$(document).ready(function() {

    window.setCookie = function(cname, cvalue, exdays) {
        var d = new Date() + (exdays||1)*24*60*60*1000;
        // defaulted to 1 day - by using "exdays OR 1" - if exdays not specified
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    window.getCookie = function(cname) {
        match = document.cookie.match(new RegExp(cname + '=([^;]+)'));
        // above is a regular expression, used to find the cookie value
        return (match ? match[1]: match); // returns cookie value or null
    }   

    // Inline Button in Table

    $("#table").click(function(e){
        alert(document.cookie);
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Firebase's onDataChange() method to update a value

Can the value be set using onDataChange() within Firebase? Without knowing the post key value of each child? Posts database databaseReference2 = firebaseDatabase.getReference("Posts"); Query query2 = databaseReference2.orderByChild("userID ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

When a user clicks on an anchor tag, close the current window, open a new window, and pass the

I have a scenario where I have an anchor tag that triggers the opening of a window on click. In this newly opened window, there is a table with a column containing another anchor tag. Here is what I am trying to achieve: Code for the anchor tag: functio ...

Ways to determine the complete list of HTML properties that can be bound to

From what I gather, Angular attempts to treat each HTML DOM element as a component and enables binding to its properties. Looking at the HTMLDivElement class, I notice it inherits the textContent property from Node and the innerHTML property from Element, ...

Resolving issues with jQuery input values

I have been working on a form that allows users to choose an amount or specify another amount. When the user clicks on "other amount," it changes the displayed amount to $5. My goal is to make it so that when the user specifies an amount other than 5, it u ...

Tell me about your past experiences using development frameworks and tools to create web applications

For the past decade, I have been developing websites on and off. Two years ago, I ventured into ASP.Net and currently, I am working on two projects simultaneously - one using ASP.Net MVC and the other utilizing Java / JSF / Spring / Hibernate. I have dabbl ...

When I tried to retrieve the value by using deferred.resolve(value) in my .then() method, it

I am currently utilizing Q.js to make an API call with two loops in my main function structured like this: for i..10 for i...5 var promise = getLoc(x,y); promise.then(function(value) { //value is undefined... ...

JavaScript: Targeting elements by their tag name within a designated container

When working with PHP, it is possible to use the getElementsByTagName method on any DOM object. However, this concept does not seem to exist in JavaScript. For example, if we have a specific node stored in the variable detailsNode, attempting to use detai ...

What is the best way to create 2 select boxes that will disable each other if they match, and then automatically choose the second option so they do not match

Is there a way to have 2 select boxes automatically change one option to the second option on one box when they match? Instead of using an "alert", I am looking for a function that can automatically update one option in one of the select boxes if they mat ...

tips for getting two ajax json Data from .net

When working with .NET, I am encountering an issue where I need to send two sets of JSON data (test1 and test2) to a .NET controller using JavaScript (ajax). Here is the code snippet for sending the data: .ajax({ type: 'POST', url ...

Show the information fetched from the MYSQL database within the content of the info window on Google Maps

Currently, I am utilizing PHP and MYSQL within Wordpress to access data from a database that includes coordinates. The purpose is to showcase markers on a Google Map. On the map, these markers are displayed with info windows containing the coordinates. M ...

Guide to navigating to a particular component in React JS

I've designed a web application using React that doesn't contain any HTML, and I've broken down each page into smaller modules. For instance, on the main page, the first module (located at the top) contains a button that, when clicked, shoul ...

Activate the extended view of a Material-UI Accordion

When using Accordions to display editable entities, we often want to keep modified entities in the expanded state. Currently, we have had to duplicate functionality by lifting up the expanded state into the accordion wrapper to prevent any controlled <- ...

Sluggish MySQL database performance

I've encountered an issue with a slow-running query. It's taking approximately 7 seconds to complete. Interestingly, when I remove the "and timestamp > 20130201" condition from the query, it executes in less than 400ms. Initially, I suspect ...

The issue of app.css and app.js resources not loading in Laravel 8 with nginx, resulting in a 404 not found error, needs to be

Although this question may appear to be a duplicate, I assure you it is different. I have thoroughly searched through Stack Overflow, Laracast, Reddit, and GitHub for a solution. My setup includes a Laravel application on an Ubuntu VM with Nginx. The pro ...

Tips for navigating through an array of images

I am attempting to create a feature similar to Snapchat stories, where an array of images is displayed for a set amount of time before returning to the previous screen. Here is an example code snippet: if (images.length > 0) { let timeout; ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

Does a Javascript event get triggered when the currentSrc attribute of an <img> element is modified?

Let's imagine we have an image tag like this: <img id="my_tag" src="/default.jpg" srcset="/small.jpg 500w, /medium.jpg 1000w, /large.jpg 2000w"> Upon loading the page, JavaScript can determine which source from t ...

The information is not being shown. Error: API expression GET is not possible

import express from 'express'; import data from './data'; const app = express(); app.get("/api/products", (req, res) => { res.send(data.products); }); app.listen(5500, () => {console.log("The server has been successfully s ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...