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

Issues with Jquery .get() function in Internet Explorer

Encountering an issue with none other than IE8. The below code, simplified for clarity, is not functioning as expected: alert('before get'); $.get(getActivityURL('ActionName',{ ts: new Date().getTime(), ...other params...}), {cac ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

Datatables fails to execute page transitions

It seems like I must be missing something, even though my code is quite basic and closely follows the example provided on the web. I am currently using server-side paging. The issue I'm facing is that upon initial page load, the data from the server ...

Mastering the art of constantly monitoring data changes in a Firebase real-time database using Vue.js

I am currently utilizing vue.js version 2 in CDN mode. I have designed 2 vue components - one that pushes data to a database and another that displays it. Here is the code snippet: firebase.database().ref().on('value', function (data) { c ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Having trouble bringing in components to my pages in ReactJS

There seems to be an issue preventing me from importing the components onto the page, resulting in this error: ERROR in ./src/pages/Home.jsx 4:0-37 Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

Using JavaScript to empty input field when switching focus between input fields

I am experiencing an issue with clearing a input number field. Here is the code snippet in question: <input class="quantity_container" v-model="length.quantity" type="number" pattern="[0-9]*" inputmode="numeric" onfocus="if (this.value == &ap ...

Challenges arise when integrating ng-model with Angular Chosen

I'm working with a table that lists users, each row ending with a button that triggers a popup form. Inside the popup, I'm using a multiple select feature with Angular Chosen to display each user's 'interests'. However, despite fet ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Failure to specify the variable type can lead to the creation of automatic global variables

Recently, I stumbled upon this http://www.w3schools.com/js/js_scope.asp page which introduced me to the concept of "Automatic Global variables". Here is an example of how it works: // You can use carName variable here function myFunction() { carName ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

Scrapy utilizes AJAX to send a request in order to receive the response of the dynamically generated

Is there a way to efficiently extract data from websites like this? To display all available offers, the "Show More Results" button at the bottom of the page needs to be clicked multiple times until all offers are shown. Each click triggers an AJAX reques ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Tips for showing images with the full path URL retrieved from JSON using AngularJS

I am currently working on a project that involves displaying images from a JSON file. The URLs of these images are stored in the JSON file. Currently, my code is only outputting the URLs themselves, which is expected. However, I am looking for a way to act ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...