Create cookie without reloading webpage

Upon a user's initial visit to a specific page, I am displaying a jQuery overlay.

The overlay includes a radio button that users can click to indicate they do not want to see the notification again.

I am interested in setting a cookie to track users who opt out of seeing the overlay.

Is it feasible to set the cookie without reloading the page?

I considered making an AJAX call to the server and setting the cookie in the response headers, but I am unsure if the cookie will be properly set during an AJAX request/response.

Is it secure/acceptable to set the cookie solely through JavaScript? Or is this not recommended?

Are there any other alternatives I should consider?

Answer №1

Setting a cookie using an AJAX call is completely feasible as it is essentially an HTTP request.

AJAX Requests Can Set and Retrieve Cookies Just Like Any Other HTTP Request

Answer №2

You can take advantage of the jQuery Cookie Plugin.

Here is a practical example:

function manageCookieSettings() {
    var $filtersContainer = $(".dynamic-filters");
    if ($filtersContainer.length > 0) {
        if ($filtersContainer.css("display") == "none") {
            $.cookie("isUsingFilters", "true", { expires: 7 });
        }
        else {
            $.cookie("isUsingFilters", "false", { expires: 7 });
        }
    }
}

Answer №3

Another option is to simply manage the cookie using vanilla JavaScript: How to Manage Cookies

Answer №4

To initiate a page reload, utilize the following code:

setcookie($data,$item_data, time()+ (3600));
echo "<script>location.href='index.php'</script>;

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

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...

What is the best method in ASP.NET Boilerplate for retrieving JSON data?

I have been facing an issue while working on this code, constantly running into the error message: Unexpected token o in JSON at position 1 https://i.stack.imgur.com/43Ewu.png I am struggling to troubleshoot and was hoping for some advice or tips on r ...

Structure of Sequelize calls

Recently, I've been working with sequelize and attempting to query my database with the code below: models.user.findOne({ where: {email: req.body.email} }, (err, existingUser) => { .... More code } Unfortunately, the code block isn't executi ...

Retrieve a JSON file from a different tab or window

My setup includes two servers: one dedicated to hosting HTML content and the other functioning as an API for connecting to Twitter. To initiate the process, I open a new tab (or window) on the HTML Server to invoke the API, which then redirects to the T ...

With the latest Facebook Graph API integration, we are encountering issues where AJAX calls are returning empty values

Exploring the latest Facebook Graph API and experimenting with fetching data using jQuery Ajax. Below is a snippet of my simple JavaScript code: var apiUrl = 'https://graph.facebook.com/19292868552'; $.ajax({ url: apiUrl, data ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

Is there a way to simulate a minified module for testing purposes?

For my project, I developed a component intended to function as a module. The implementation involves the utilization of third-party code provided in the form of a config file (initOpinionLab.js) and a .min.js file (opinionlab.min.js). As part of the devel ...

Javascript regular expression fails to find a match

Is there a way to match all strings except for the ones containing '1AB'? I attempted it but it returned no matches. var text = "match1ABmatch match2ABmatch match3ABmatch"; var matches = text.match(/match(?!1AB)match/g); console.log(matches[0]+" ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

In React Router version 4, it is stated that each router is only allowed to have a single child element when using multiple routes

I'm currently working on implementing a sidebar alongside the main content area using react-router-dom. Instead of just rendering <Sidebar/> directly, I want to pass it the location prop due to another issue where clicking a <Link/> in the ...

Basic $http.get request including parameters

I've been attempting to send an HTTP request using the AngularJS $http service like this: $http.get('http://myserver:8080/login?', { params: {username: "John", password: "Doe" }, headers: {'Authorization': ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

Is the data missing in the initial request?

After creating a function that returns an object with mapped values, I encountered an issue. The second map is undefined the first time it runs, causing my vue.js component to display data from the first map but not the cutOff value. Strangely, when I re ...

Adjusting canvas context position after resizing

I've been experimenting with using a canvas as a texture in three.js. Since three.js requires textures to have dimensions that are powers of two, I initially set the canvas width and height to [512, 512]. However, I want the final canvas to have non-p ...

The function tokenNotExpired encounters an error when attempting to access the localStorage, as it

I am looking to incorporate the angular2-jwt library into my project: https://github.com/auth0/angular2-jwt However, I encountered an exception when attempting to call the tokenNotExpired function: Exception: Call to Node module failed with error: Refe ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

The AJAX call for fetching logged in users is coming back as undefined

Hey there! I'm currently diving into the world of AJAX and am working on enhancing the user experience on my admin system. One thing I want to achieve is to update information like online users, messages, tasks, etc. every 30 seconds or so (for testin ...