JS cookies refresh itself when the page refreshes - javascript

I need to use cookies for my new webshop, so if the page refreshes the old values will stay in.
Now i've created my cookies, and it works perfectly fine, but when I'm refreshing the page, the cookie goes empty again. If i'm going to a different page, the cookie stays (path:/)
Now i'm confused and need someone to clarify what i'm doing wrong right here, so I came here to ask my question!
Here is the code im using
$.cookie.raw = true;
$.cookie.json = true;
$.cookie('cart', unescape);
function UpdateTotals() {
TotalPrice = 0;
for (var i = 0; i < Orders.length ; i++) {
var SearchResult = SubMenuItems.filter(function(v) {
return v.submenu_id === Orders[i];
})[0];
TotalPrice += parseFloat(SearchResult.price);
$.cookie('cart', JSON.stringify(Orders), { expires: 7, path: '/' });
Now if I click on some orders, the cookies stays filled with the jSon values.

Related

Open pages with user lists and download the user ids

So I have a page which has a list of users, my total list of users is separated into 10 pages with each page showing 20 users. I want to open each page in a new window, pull the user ids on that window, close the window, and open the next page. Later I'll compile all this into a report. The problem I seem to be having is that the user_id_list only gets populated by the users on the first page so I have a bunch of duplicates.
Some of the code for parsing the pages.
full_page_string = document.getElementsByClassName("pagination")[0].outerText;
index_of_next = full_page_string.lastIndexOf("Next");
last_page_number = full_page_string.substring(index_of_next-3, index_of_next);
last_page_number.trim();
last_page_number = 2; /*DELETE LATER*/
page_array = [];
user_id_list = [];
/*Programatically create an array of pages*/
for (var page_num = 1; page_num <= last_page_number; page_num++) {
url = "example.com/users/"+ user_account_id + "/friends?page=" + page_num;
/*Open Each Page*/
var loaded_page = window.open(url, "page_" + page_num, "width=400, height=600");
page_array.push(loaded_page)
/*
For loop keps going even with settimeout. See if there is a way to delay a forloop. The thing is we need enough time to load a page, wait for it, grab users, close page, load a new page and repeat. Right now the floor loop makes it too fast.
Maybe Asyncronously open each page so they're their own instance or "thread"?
*/
loaded_page.onload = function () {
/*Find all users on the page by class*/
friends_on_page = document.getElementsByClassName("link span f5 fw7 secondary");
for (var i = 0; i <= friends_on_page.length; i++) {
pathname = friends_on_page[i].pathname;
user_id = pathname.substring(pathname.lastIndexOf("/")+1)
user_id_list.push(user_id)
console.log(user_id)
}
loaded_page.cose()
};
}

How to keep input and page the same using local storage

Hi I wrote a code which has a working search with filters applied to it. The only problem I am having is that it doesn't stay the same as to how the filters where set when the user closes or refreshes the webpage. I am not using a checkbox
This is my code so far
saveTask: function(name, isCompleted) {
window.localStorage.setItem(name, isCompleted);
},
renderTasks: function() {
for (var i = 0; i < window.localStorage.length; i++) {
var taskName = window.localStorage.key(i);
var isCompleted = window.localStorage.getItem(taskName) == "true";
var taskHTML = Todo.template.replace("<!-- TASK_NAME -->", taskName);
if (!isCompleted) {
Todo.container.insertAdjacentHTML('afterbegin', taskHTML);
}
}
}
This is a js fiddle https://jsfiddle.net/4p8awnqx/6/
I am trying to keep the filters the same using local storage so that when it is closed or refreshed it stays the same

Reload a content almost invisibly and no blinking effect using JAVASCRIPT

I'm writing a small progam wherein I'm getting data using $.get then display the data so far so good and then there's this part then when I click a certain link it refresh the page but it has this blinking effect. Is there a way on how to reload the content get the new updated content then replace the previously loaded data.
NOTE: I didn't use setInterval or setTimeout function because it slows down the process of my website. any answer that does not include those functions are really appreciated.
Here's the code
function EmployeeIssues(){
$('#initial_left').css({'display' : 'none'});
var table = $('#table_er');
$.get('admin/emp_with_issues', function(result){
var record = $.parseJSON(result);
var data = record.data,
employees = data.employees,
pages = data.pages;
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
}else{
$('#er_tab_label').html('<b>No employees with issues yet.</b>');
}
});
table.html('');
}
then this part calls the function and display another updated content
$('#refresh_btn').on('click', function(e){
e.preventDefault();
var tab = $('#tab').val();
if(tab == 'er'){
EmployeeIssues();
}
});
What should I do to display the content without any blinking effect?
thanks :-)
This section might be the issue :
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
} else ...
It seems you're asking table_er to fade in once per run of the loop whereas s there can only be one such table, you only need to do it once ?
first try re-arringing it like this:
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
table.append(write_link(employees[i])); // function that displays the data
}
$('#table_er').fadeIn('slow'); // only do this after the table has all its html
if(pages){
$('#pagination').html(pages);
}
} else ....
Another possibility is that you're running through a loop and asking jquery to do stuff while the loop is running. It might be better to work out the whole HTML for the new page data in a string and then get the screen to render it in one line. I cna't do this for you as I don't know what's in write_link etc but something like this ..
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
var sHTML ="";
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
sHTML+=write_link(employees[i]); // maybe this is right ? if write_link returns an HTML string ?
}
table.append(sHTML); // add the HTML from the string in one go - stops the page rendering while the code is running
$('#table_er').fadeIn('slow'); // now show the table.
if(pages){
$('#pagination').html(pages);
}
} else ...

How to reload the page when implementing the History API

I am trying to use the History API to allow me to use the back and forward buttons when loading content dynamically. Here is the code I am using, and an example of the state object I am using too.
How I am using the state object and pushstate()
var stateObj = {Content : homeSection.innerHTML, "Product" : detail.Name, Title : title.innerHTML, Section:"dynamicArticle"};
window.history.pushState(stateObj, "", detailName);
window.addEventListener('popstate', function(event) {
updateContent(event.state);
});
Function used:
function updateContent(stateObject) {
if (stateObject){
homeSection = document.getElementById(stateObject.Section);
homeSection.innerHTML = stateObject.Content;
title.innerHTML = stateObject.Title;
var items = document.querySelectorAll(".homeItem");
if(items){
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
}
checkoutButton = document.getElementById('checkoutButton');
if(checkoutButton){
checkoutButton.addEventListener('click', function(){
displayCheckout();
});
}
basketButton = document.getElementById("basketButton");
quantityInput = document.getElementById("productQuantity");
if(basketButton){
basketButton.addEventListener('click', clicked);
basketButton.addEventListener('click', updateBasketNumber);
quantityInput.value = "1";
}
searchSort = document.getElementById("sort");
if(searchSort){
var items = document.querySelectorAll(".searchResult");
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
searchSort.addEventListener("change", function(){
sort = searchSort.value;
searchItem(e, sort);
});
}
}
else{
return;
}
}
What I am struggling with is that if I navigate to one of the pages using the pushState() and I try to reload the page, as you would expect the page cannot be found.
I am asking if there is a way to allow a reload or for someone to navigate to the URL without it giving an error, and giving the correct content
Just like #jon-koops pointed in the comment you need to configure your server to redirect requests to the same page where all you links branch.
If you are using apache 2.2.16+ it get's as simple as:
FallbackResource /index.html
This will rewrite all URL’s to a single entry point that is index.html page.
Other solutions depend on the server you are running.

If <div id> Removed From HTML Document Then Redirect to a New Web Page

If a specific <div id> is removed from the HTML document, I want it the user to be redirected to a new web page using JavaScript.
For example:
<div id="credits"></div>
If someone removes it then users will be automatically redirected to my website.
This is to protect copyrights.
The best you can probably do is to just poll for the existence of that div, and redirect if it's not there. Also, be sure to check that it's actually visible, per Philip's comment.
But of course any user can just turn this script off, so I'm really not sure it's even worth the effort.
setInterval(function(){
if (!$('#credits:visible').length) window.location.href = 'wherever.com';
}, 3000);
You want a MutationObserver, but it's not widely supported: http://jsfiddle.net/xNAXd/.
var elem = document.getElementById("credits");
new MutationObserver(function(mutations) {
for(var i = 0; i < mutations.length; i++) {
var index = Array.prototype.indexOf.call(mutations[i].removedNodes, elem);
if(~index) {
alert("Deleted!");
break;
}
}
}).observe(elem.parentNode, {
childList: true
});

Categories

Resources