Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the next time they visit the page, their name will be displayed inside a span element.

Here is what I envision through pseudocode. I hope it clarifies my intention....

If a cookie named "name" exists, then display the stored information within a "span" tag

Otherwise,

Save the user's input as a cookie when they submit the form

(Note: My submit button is defined with type="submit")


@banana, I've made adjustments to my code to ensure alignment with all tag names and ids used. However, upon entering a name into the form, submitting it, and revisiting the page, nothing appears in the span element.

function setCookie(cname, cvalue, milliseconds) {
    var d = new Date();
    d.setTime(d.getTime() + (milliseconds));
    var expires = "expires=" + d.toGMTString();
    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].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

document.onload = checkIfCookieExists;
function checkIfCookieExists(){
var firstNameFromCookie = getCookie('firstName');
if(firstNameFromCookie == ''){
   // cookie hasn't been set

}
else{
   // cookie has been set
   var display = document.getElementsByTagName('span')[0];
   display.innerHTML = firstNameFromCookie;
}
}

function init(){
 var firstName = document.getElementById('firstName').value;
 var cookieExpieryTimeInMilliseconds = 1000 * 60 * 60; //1000 milliseconds * 60 seconds * 60 minutes - resulting in a cookie expiration time of 1 hour.
 setCookie('firstName', firstName ,cookieExpieryTimeInMilliseconds );
}

window.onload = function(){
  init();
};

Answer №1

If you need to access cookies, the Hera.js library provides a convenient hera.getCookie() function.
hera.getCookie() operates in the following way:

  • All cookies are combined into a single string, document.cookie
  • hera.getCookie() extracts the desired key from this string
  • A string containing the value is then returned.

For instance, by setting a cookie with

document.cookie = "love=chocolate"
, you can utilize hera.getCookie("love") to receive the value of chocolate (as a string).

To make use of the Hera.js library, simply include

<script src="https://rawgithub.com/thetakeaway/hera.js/master/hera.js"></script>

within the <head></head> section of your HTML document.

Cheers and happy coding!

Answer №2

Utilize the functions provided in this code snippet to manage cookies effectively. Use the getCookie function with the desired name and check if an empty value is returned.

For client-side implementation:

function setCookie(cname, cvalue, milliseconds) {
        var d = new Date();
        d.setTime(d.getTime() + (milliseconds));
        var expires = "expires=" + d.toGMTString();
        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].trim();
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
    }

EDIT:

document.onload = checkIfCookieExists;
function checkIfCookieExists(){
    var firstNameFromCookie = getCookie('first_name');
    if(firstNameFromCookie == ''){
       // Cookie was not set

    }
    else{
       // Cookie was set
       var yourSpan = document.getElementById('yourSpansID');
       yourSpan.innerHTML = firstNameFromCookie;
    }
}

To save a cookie using the provided functions above, follow these steps:

function whatever_Function_You_Use_To_Submit_Users_Details(){
     var firstName = ... retrieve the first name entered by the user
     var cookieExpieryTimeInMilliseconds = 1000 * 60 * 60; //1000 milliseconds * 60 seconds * 60 minutes - equals 1 hour.
     setCookie('first_name',firstName ,cookieExpieryTimeInMilliseconds );
}

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

Issue encountered: Unable to locate the file "SignInScreen" within the directory "./src/screens/authScreens" as referenced in the file "App.js"

App.js: import { StyleSheet, Text, View, StatusBar } from "react-native"; import { colors, parameters } from "./src/global/styles"; import SignInScreen from "./src/screens/authScreens/SignInScreen"; export default function A ...

React State Update Triggered by Changing Hidden Input/Textarea Value - No User Input Required

To activate a function when the contents of a hidden input, textarea, or textfield change in React without requiring user input to trigger it, you will need to dynamically adjust the value of the hidden input and then have the function automatically exec ...

Harvest Data from JSON Data Structure

My query pertains to handling data received from a URL in JSON format. Most examples I've come across focus on recursively printing symmetrical JSON objects, like this one. However, how can I effectively print the contents of the following JSON object ...

utilizing the identical characteristics of the parent component

In order for the properties in InputGroup.js to be accessible as this.props in lower-level components like TextInput.js, Checkbox.js, I have created a simple component called InputComponent.js. In this component, I assign this.props to this.prpt so that it ...

Automated resizing for various monitor dimensions in HTML

Is there a way to dynamically adjust the zoom level on an HTML webpage based on the monitor size? For instance, an image that appears large on a laptop screen may look small on a PC monitor. Is there a solution available to scale the picture size as the mo ...

Generate SVG components without displaying them

Is there a way to generate a custom SVG graphic through a function without the need to attach it to any element? Can I simply create an empty selection and return that instead? Here is my current implementation: function makeGraphic(svgParent) { retur ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

How can I use Angular to bind the text entered in an `input` within one `ng-repeat` `div` to another `div` within a different `ng-repeat`?

I am trying to create a dynamic Angular-based webpage where input tags are connected to h3 tags in separate DIVs. Below is the setup of my HTML page (as seen on Plunker): <!DOCTYPE html> <html> <head> <style type="text/css> ...

Is there a way to upload numerous images from my local disk onto a canvas using Fabric.js?

I'm currently working on an innovative Image Collage application using the power of HTML5 canvas and Fabric.js. One of the key features I want to implement is the ability for users to simply drag and drop files into the designated 'File Drag and ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Displaying an Ajax progress bar during the page loading process

For my current project, I am required to implement a progress bar during the Page load event. The scenario involves receiving a request from another application, which triggers the creation of a PDF file on my page. Since this process can be time-consumi ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

The AWS API Gateway quickly times out when utilizing child_process within Lambda functions

I'm encountering an issue with my Lambda function being called through API Gateway. Whenever the Lambda triggers a spawn call on a child_process object, the API Gateway immediately returns a 504 timeout error. Despite having set the API gateway timeou ...

Is there a way to customize the appearance of a MUI5 Tooltip using emotion?

I went through the information in this Stack Overflow post and experimented with the styled method. The code snippet I used is as follows: import * as React from 'react'; import { styled } from '@mui/material/styles'; import Tooltip, { ...

Hover shows no response

I'm having trouble with my hover effect. I want an element to only be visible when hovered over, but it's not working as expected. I've considered replacing the i tag with an a, and have also tried using both display: none and display: bloc ...

PHP AJAX POST not functioning as expected

Can someone please help me with my AJAX code issue? I've created many posts before, so I'm confused about why this one isn't working. Here is the code: $(function() { $("#btnSubmit").click(function(event) { event.preventDefault(); ...

Verifying email availability using VB.NET WebMethod, JSON, and CustomValidator

I have been researching this issue extensively, both on this site and others, but have yet to find a solution that works for me. My goal is to validate whether a given email address is already in use in a database during the registration process. On my Re ...

Change the size of the font with a slider in VueJS

I have been utilizing the project found at This particular project allows end-users to reuse Vue components as editable sections by providing a styler overlay for adjusting content within a div or section. After installation, I added a slider which now ap ...

`Nextjs customizes the position of locales`

Currently implementing i18n translation in my project, the default root appears as follows: https://example.com/en/business/transaction Is it possible to customize the root to appear as: https://example.com/business/en/transacation Thank you. ...

I encountered an error stating that ".then" is not defined during my attempt to save

Just starting out with node.js and I encountered an issue: TypeError: Cannot read property 'then' of undefined This is the code snippet causing the problem: router.post("/signup", (req, res) => { const userRegister = new UserRegister({ ...