Cookie is overwriiting issue - javascript

I have following code I use Jquery cookie plugin to set cookie.I need to store multiple values to a a cookie variable using jquery but every time its overwrite so multiple value doesn't store.please have a look into my code and help me.I have a select box and its name is inserted into a cookie variable every time.
$(".cookieul").on("click",function(){
var a ='';
var myCookies = [];
var newValue = $(".client option:selected").text();
a += newValue;
myCookies.push(a);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
});

You may write like this -
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();// your new selected text
var old_value_json = $.cookie("example"); // check your plugin get cookie syntax
var old_value_arr = [];
old_value_arr = $.parseJSON(old_value_json); //converting your stored JSON string to javascript array
old_value_arr.push(newValue ); // pushing new value to array
$.cookie("example", JSON.stringify(old_value_arr ), { expires: 7 });//setting new value to cookie
});

This solves the issue.Any other better way
var myCookies = [];
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();
var old_value_json = $.cookie("example");
myCookies = $.parseJSON(old_value_json)
myCookies.push(newValue);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
var storedAry = JSON.parse($.cookie('example'));
console.log(unique(storedAry));
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
});

Related

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Show all objects present in localStorage on a webpage

I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.
You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})

How can I dynamically create unique objects within .each()?

I'm running a .each() on a list of items and categorizing those items in my HTML. In a function after that I'm checking which of those items is checked (checkboxes). In my function (prepareTrainings();) that finds which boxes were checked, I need it to display data from the result of the .each(). Basically, if the user checked X checkbox, show the Course Name and URL for that item...
My question: I'm not sure what would be best practice. Should I be creating an object to store those values inside my if(trainingGroup etc.) statements?
$.ajax({
url: "mySite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
var dynCourseId = courseName.replace(/\s+/g, '')
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
function prepareTrainings() {
var idSelector = function() {
return this.id;
};
var checkedCourses = $(":checkbox:checked").map(idSelector).get();
alert("IDs for Courses Selected: " + checkedCourses);
}
Keeping your processed objects in a global var makes sense. Define e.g. an object like so:
var courses = {};
Then in your .each function, extract the information from your HTML elements like you already do and store each result in another object:
$.each(data.d.results, function(index) {
var $this = $(this);
var course = {}; //Create empty object
course.name = $this.attr('Title');
course.number = $this.attr('Course_x0020_Number');
course.url = $this.attr('URL');
course.trainingGroup = $this.attr('Training_x0020_Group');
course.recurrence = $this.attr('Recurrence');
course.id = course.name.replace(/\s+/g, '')
//Store your course by id in the courses object
courses[course.id] = course;
//...
Later when checking which checkboxes are checked, you can retrieve the information of each course like so:
var checkedIDs = $(":checkbox:checked").map(idSelector).get();
var course = courses[checkedIDs[0]]; //fetches the first selected course
//Now you can do whatever with the data, like print lists...
(...).innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+course.id+'"/>'+course.name+course.recurrence+'</li></ul>';
I hope I understood your question correctly, if not leave a comment.

Javascript: creating dynamic variables and object names. / html5 localstorage

I'm working on a form that is saved by HTML5 local storage.
When pressing save:
function saveAll(){
var field1 = document.getElementById('field1').value;
localStorage.setItem('con_field1',field1);
var field2 = document.getElementById('field2').value;
localStorage.setItem('con_field2',field2);
var field3 = document.getElementById('field3').value;
localStorage.setItem('con_field3',field3);
var field4 = document.getElementById('field4').value;
localStorage.setItem('con_field4',field4);
var field5 = document.getElementById('field5').value;
localStorage.setItem('con_field5',field5);
var field6 = document.getElementById('field6').value;
localStorage.setItem('con_field6',field6);
}
And when loading the page (fills out the forms):
function ShowAll() {
var field1 = localStorage.getItem('con_field1');
document.conditioning.field1.value = field1;
var field2 = localStorage.getItem('con_field2');
document.conditioning.field2.value = field2;
var field3 = localStorage.getItem('con_field3');
document.conditioning.field3.value = field3;
var field4 = localStorage.getItem('con_field4');
document.conditioning.field4.value = field4;
var field5 = localStorage.getItem('con_field5');
document.conditioning.field5.value = field5;
var field6 = localStorage.getItem('con_field6');
document.conditioning.field6.value = field6;
}
This all works fine, but I want to re-write this in a more fancy and efficient way. I was thinking of something like this:
function ShowAll() {
var field = [];
for (i=0; i<6; i++) {
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
}
But the browser is not enjoying this. Basically I need to create a loop that automatically changes the "field" name in to 'field1, field2, field3' etc. The window thing is working, but I'm just using it wrong.
Anyone has an idea?
Thanks a lot!
function showAll(t1,c1,d1) {
var field1 = localStorage.getItem('con_field1');
console.log(field1)
var field2 = localStorage.getItem('con_field2');
var field3 = localStorage.getItem('con_field3');
}
You should add all of your data to one object, stringify it, then add that to local storage under a single key.
When you load it, grab the one local storage item, parse it, then access the properties on the object.
e.g.
var save = function () {
var data = {
foo: 'bar'
};
localStorage.setItem('myData', JSON.stringify(data));
};
var load = function () {
var data = JSON.parse(localStorage.getItem('myData'));
var someProp = data.foo; // gives you 'bar'
};
It looks like your main problem is that the fields are indexed beginning with 1, but your loop indexes from 0.
What about this?
var field = [];
for (i = 1; i <= 6; i++)
{
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
Also, I'm not 100% on this, but I think using document.getElementByID is more cross-browser compatible than using bracket notation on the window object, but it's been a while since I wrote plain vanilla JS, so don't quote me.
I would try document.purpose["field" + i].value = window['con_field' + i].

Generating JSON Object

I'm trying to parse the rows in a table that I generate using Javascript by adding items to a cart and then create a json object when the user hits save order of all the items and pass it to a php script using $.post in jQuery.
The only trouble I'm having is understanding JSON objects and how to push more items onto the object. I get an error in firebug telling me that devices[i] is undefined. Not really sure how else to accomplish this. I thought it was really just an array.
function Save()
{
var devices = new Object();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
You currently have devices declared as an object, but you're treating it like an array.
You need to declare it as an array of objects.
function Save()
{
var devices = new Array();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i] = new Object();
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
or something like that.
(Updated to show it in your code)

Categories

Resources