jQuery update cookie value - javascript

I am using jquery-cookie library to create cookie with JQuery. How can I update value of the cookie? I need it create new cookie and if the cookie exists to update it. How can I do this?
Code that I got:
v.on('click', function(){
var d = $(this).attr('role');
if(d == 'yes')
{
glas = 'koristan.'
}else {
glas = 'nekoristan.'
};
text = 'Ovaj komentar vam je bio ' + glas;
//This part here create cookie
if(id_u == 0){
$.cookie('010', id + '-' + d);
}
$.post('<?php echo base_url() ?>rating/rat_counter', {id : id, vote : d, id_u : id_u}, function(){
c.fadeOut('fast').empty().append('<p>' + text).hide().fadeIn('fast');
});
})

To update a cookie all you need to do is create a cookie with the same name and a different value.
Edit
To append your new value to the old...
//Im not familiar with this library but
//I assume this syntax gets the cookie value.
var oldCookieValue = $.cookie('010');
//Create new cookie with same name and concatenate the old and new desired value.
$.cookie('010', oldCookieValue + "-" + id);

watch out for this link
http://www.electrictoolbox.com/jquery-cookies/
here you see all important thing you can do with cookies.
if you want to know if an cookie already exists, just use this
if($.cookie("example") != null)
{
//cookie already exists
}

Related

JS - Cookie management

I made this little code using JS to disable cookies:
$(document).ready(function() {
var cookie_settings = getCookie("cookie-settings"); //Main cookie which contains cookie preferences
var cookie_selector = document.getElementById("cookie-selector"); //Modal for cookie selection
var g_recaptcha = document.getElementById("cookie-g-recaptcha"); //Example checkbox cookie
var g_tag_manager = document.getElementById("cookie-g-tag-manager"); //Example checkbox cookie
var messenger_plugin = document.getElementById("cookie-fb-mccp"); //Example checkbox cookie
var g_analytics = document.getElementById("cookie-g-analytics"); //Example checkbox cookie
var cookie_set = document.getElementById("cookie-set"); //Button to save preferences
if (cookie_settings == null) { //Check if main cookie exist
$(cookie_selector).modal({
backdrop: 'static',
keyboard: false
}); //If not exist, open cookie selector modal
} else {
var cookie_settings_raw_values = getCookie("cookie-settings"); //read and save main cookie in var
var cookie_settings_values = cookie_settings_raw_values.split('&'); //save main cookie content in array
if (cookie_settings_values.includes(g_recaptcha.id)) {
//If array contains recaptcha example include it
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_tag_manager.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(messenger_plugin.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_analytics.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
//or you can remove else condition and manage this part from php
}
$(cookie_set).click(function() { //on save preferences click
var selected_cookies = [g_recaptcha.id, g_tag_manager.id]; //make array and include required cookies
if (messenger_plugin.checked == true) {
//if messenger plugin example checkbox is checked push it's reference in array
selected_cookies.push(messenger_plugin.id);
}
if (g_analytics.checked == true) {
//same for the other optional checkboxes
selected_cookies.push(g_analytics.id);
}
var expiry_date = new Date();
expiry_date.setMonth(expiry_date.getMonth() + 6); //expiration date 6 months in my case, you can set what you want
document.cookie = document.cookie = "cookie-settings=" + selected_cookies.join('&') + "; expires=" + expiry_date.toGMTString(); //make main cookie with required and optional selected checkboxes (the deadline is 6 months after the creation of the cookie)
location.reload(); //reload page
});
//get cookie by name
function getCookie(name) {
var document_cookie = document.cookie;
var prefix = name + "=";
var begin = document_cookie.indexOf("; " + prefix);
if (begin == -1) {
begin = document_cookie.indexOf(prefix);
if (begin != 0) {
return null;
}
} else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = document_cookie.length;
}
}
return decodeURI(document_cookie.substring(begin + prefix.length, end));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My question is it enough to disable third-party cookies?
Not including the scripts if the user does not accept cookies, do the stored ones become useless? Does the site comply with the GDPR?
If not, do you have any other valid alternative to propose that is not the use of third party codes?
Most of the websites, which are trying to be GDPR compliant are not loading any of these scripts by default (as you probably do). First they show a popup, if a user wants to load e.g. tracking cookies and if the user agrees they will be loaded. The configured setting which services should be loaded / what the user has selected will then be stored either in a cookie or e.g. the localStorage.
So yes, your site seems to be GDPR compliant when we take a look at the approach how you load the external scripts.
If you’re talking about deleting them, set it again with the expiry date before today.

Page reload not reflecting database updates

I have a dropdown list on an update agent profile form where a user can select an item, referred to as a "master" in the database. However, if they select the item "Create New Master", they can enter a value in a blank text field and click a corresponding button. This updates the "Create New Master" value in the database to be whatever the value they entered is, and creates a new value in the database as the new "Create New Master" value. This also updates the agent table in the database to have the new master's ID saved to it, changing whatever the previous ID was. All of the database functionality works, and all the changes are made. However, I need to reload the form with the new values. How can I reload this? We use spring and hibernate, but I'm using Javascript for most of the functionality on this form page.
I've tried using window.location.reload(true), but this doesn't work. If the page kicks the user from the profile and then the user manually re-enters the profile of the same agent, the updated values show, but this is obviously less than ideal.
function addMaster(obj){
//Create lots of relevant variables that are used for the database update.
if(newName == null || newName == ""){
alert("You have to enter a new name to add it.");
}
else{
var jsonURL = '${urlBase}/addMaster/' + newName + '/' + updated + '/' + updateID + '/' + created + '/' + createID + '/' + create + '/' + agentID + '.json?jsoncallback=?';
var xhttp = jQuery.getJSON(jsonURL, function(obj, textStatus){
});
window.location.reload(true);
}
}
This calls to another file, which updates the database accordingly and correctly, but the reload doesn't change the new selection in the dropdown list. It shows the old one, even though checking the database shows that it has truly been updated. How can I make the current database values be reflected on the page without having to make the user leave the profile?
The method jQuery.getJSON is asynch so you reload the page before the call is completed. You should reload the page after that you request completed so you should do something like this:
function addMaster(obj){
//Create lots of relevant variables that are used for the database update.
if(newName == null || newName == ""){
alert("You have to enter a new name to add it.");
}
else{
var jsonURL = '${urlBase}/addMaster/' + newName + '/' + updated + '/' + updateID + '/' + created + '/' + createID + '/' + create + '/' + agentID + '.json?jsoncallback=?';
var xhttp = jQuery.getJSON(jsonURL, function(obj, textStatus){
//this is the success function.. asynch call is done
window.location.reload(true);
});
}
}

Reg Ex doesnt validate if i use # along with other characters or number

this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.

Setting session in php from value being set in the page

I'm trying to set a php session onload
$_SESSION["tusername"] = $_POST['ttuser'];
however my value is being set in jQuery on $(function() {
$('#ttuser').val(tusername);
When the page is loaded, the session is not set as I believe the session is being set before the textbox value is set by jQuery. I tried using ajax to post a value to the page, but it doesn't retrieve it.
The only way I am setting the session now is on a button click, the exact same way.
Any ideas?
Thanks in advance
EDIT
Here is the Function at the start where everything is set, as requested
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.authenticatedd').removeClass('hidden');
} else {
$('.welcometitle').html('<strong>Not yet connected with Twitch?</strong>');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
var token = Twitch.getToken();
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read', 'channel_editor', 'channel_commercial', 'user_subscriptions', 'channel_check_subscription']
});
})
Twitch.api({method: 'channel'}, function(error, channel) {
$('#streamkey').text(channel.stream_key);
});
Twitch.api({method: 'user'}, function(error, user) {
var tusername = user.display_name;
var tlogo = user.logo;
$('#twitchname').text(tusername);
$('#ttuser').val(tusername);
$.get("setsession.php?ttuser="+tusername, function(){
});
console.log(tlogo);
if (tlogo != null)
$('#twitchlogo').attr('src', tlogo);
$.cookie('logo', tlogo, { expires: 14, path: '/'});
$('.sidename').html('<strong>' + tusername + '</strong> Logged in');
var currentdate = new Date();
var datetime = currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
var items = [];
items.push('<li><div class="xe-comment-entry"><div class="xe-comment"><span class="label label-success">Status</span><p><span class="label label-danger">' +datetime+ '</span> Logged in</p></div></div></li>')
$('#eventlog').prepend( items.join('') );
});
});
Why dont you just make a request to a php file which will initiate the session.
myfile.php
<?php
session_start();
$_SESSION["tusername"] = $_REQUEST['ttuser'];
echo "Session is : "+$_SESSION["tusername"];
?>
HTML
$(function(){
$.get("myfile.php?ttuser="+tusername, function(data){
console.log(data);
});
$('#ttuser').val(tusername);
});

how to delete particular cookie from cookies using jQuery

This is code which shows URL and delete image for delete cookie. add and display function is working but how to delete ??
function backLinks(){
var pathname = window.location;
var patientName = document.getElementById("general:patientDetailName").value;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
// for writing Cookie
var stringCookie = "<span class='backLinkText1'><img src='../images/deleteImg.png' alt='' class='backLinkDeleteButton' onClick='deleteBackLink()'/></span><a class='backLinkText' href=\""+pathname+"\"> Patient History For \""+patientName+"\"</a>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
**
function deleteBackLink(val){
jQuery.cookie(val, null);
}
**
How can I create a delete function and what parameter will I pass to it?
got a correct answer ...
in this i will replace cookie and delete inner html
function backLinks(stringValueAndName, patientName, patientDOB){
var pathname = window.location;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
var time = new Date();
var spanId = time.getTime();
// for wright in Cookie
var stringCookie = "<span id ="+spanId+"> <img src='../images/deleteImg.png' class='backLinkDeleteButton' onClick='deleteBackLink("+spanId+")'/><a class='backLinkText' href=\""+pathname+"\">"+stringValueAndName +patientName+' ('+patientDOB +')'+"\</a></span>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
function deleteBackLink(val){
jQuery('#'+val).remove();
var stringCookie = jQuery('#backButtonSpan div').html();
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
}
To delete a cookie with jQuery, set the value to null:
jQuery.cookie("name", null);
So your function will work - just pass the cookie name as a parameter:
deleteBackLink("name");
It doesn't. A cookie is a cookie.
The closest it comes is the HTTP Only flag, which allows a cookie to be hidden from JavaScript(mean client side). (This provides a little defence against XSS cookie theft).
A cookie is a cookie. (Again, client side code can't touch an HTTP only cookie)

Categories

Resources