AMP set and get cookies values - javascript

I am new in this AMP. In web I have scenario like below.
Example I have a page with 100 paragraphs content ... For the user first time visit the page displaying only 10 paragraphs of content. then will ask to user email address in input form. after user provide the email address then will display remaining 90 paragraphs content... The same user visit 2nd time that page we displayed the content without asking email.
Implementation Logic in WEB
After user enter the email address we stored the values in cookies.
If the user visit 2nd time based on cookie values we display the content..
So same logic needs to implements the AMP pages.
I design the form in amp and other stuff but struggling to set the cookie values..
The following code I am used in WEB:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Once user enter the email and submit the form
setCookie('article-page','email','XXXXX');

You can't directly access cookies from within an AMP page. However, you can use the amp-access component to implement this behavior server-side.
You can ignore the login/logout features provided by amp-access. The only thing you need to do is to change the response for the authorization endpoint to either return true or false depending on whether the user has provided an email address. Based on this information you can then adjust the content that is displayed on the page.

You can set cookie from server-side using amp-state with credentials="include" attribute. Add this amp state in your body html:
<amp-state credentials="include" id="myState" src="https://example.com/data-state"></amp-state>
And set cookie from server side from the source url https://example.com/data-state:
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1day
Or get cookie from server-side:
if(!isset($_COOKIE['user'])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}

Related

How to save info in database when user favorites?

I'm failing to save the info to when a logged in user clicks on the favorite button.
This is my first week in javascript class(including ajax). We're allowed to copy paste as long as we understand the process. So the first thing I did was looking up tutorials as to how to make favorite / unfavorite buttons and took over a template. Then I searched up how save the info in the database once the user clicks the favorite button. I'm not sure linking to external websites is allowed but I specifically took over this code:
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
faves = myfaves;
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
</script>
</head>
<body>
Add me to fav
<ul id="appendfavs">
</ul>
</body>
</html>
It displays "add me to fav" like it's supposed to but then when I click on it, it returns:
(index):54 Uncaught TypeError: Cannot read property 'push' of null
at HTMLAnchorElement.<anonymous> ((index):54)
at HTMLBodyElement.dispatch (jquery.min.js:3)
at HTMLBodyElement.r.handle (jquery.min.js:3)
The assignment is as follows:
""- Show a 'favorite' icon / heart. Make this clickable via jQuery / JavaScript. If you click on it, an AJAX request must be sent with the blog post id. A WP plugin must 'process' the AJAX request, and store in the session (or database) that user X has liked a certain blog post. The server must return a JSON response."
Now had a small side question, for after I resolve the error of this thread, is my way of thinking correct:
Through CSS I'll create a heart button
This script itself does the ajax request with post ID
WP plugin I've done before
This script provides the JSON response
Thank you stack overflow in advance, I look forward to learning!

how to delete a cookie if the browser crashes

I have a situation in my application where the users should are not allowed to open multiple instances of the application in a browser. So we are reading the cookies, if there is a session already opened we alerting the user that they are attempting to open multiple sessions.Some times if the browser crashes for some reason the browser is still having the old cookie and when the user is attempting to open the application again the browser is not allowing the user to login. User has to manually delete the cookie from the browser history. The business doesn't want that process.FYI I am using angularJS
Found the same question in other post but didn't find an answer I want here Can someone please help me out with this. Thanks in advance!
I came up with the following code. But when the application crashes the cookie is still sitting in the browser and not allowing the user to login at all. The only workaround for me now is to delete the cookie manually from the browser and login.
var duplicateApp = false;
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
window.onload = function(){
var MyAppCount=readCookie("MyApp");
if (MyAppCount > 0) {
duplicateApp = true;
alert("You are attempting to open multiple application sessions.\n\nPlease close any existing application from the web browser before restarting the application.");
var win = window.open("about:blank", "_self"); win.close();
}
else {
duplicateApp = false;
createCookie("MyApp", 1, 1);
window.onunload = function(){
if (duplicateApp == false) eraseCookie("MyApp");
};
}
};
Could you please suggest any changes I have to make to restrict the user to open only single instance of the application.
I would typically handle this on the login page by creating a new session and invalidating the old one when a user logs in again with the correct credentials.

Javascript Cookie Not Setting

I have an application that needs to pop a URL based on a Query String sent to it. Unfortunately, we can't insert any javascript into the application itself, but we can insert an iFrame that loads a page running javascript. There is a bug in the application where it loads the content in the iFrame twice within a couple seconds, which results in the URL popping twice.
To resolve this, I decided to set a cookie with an expiration. Before popping, I would check to see if the cookie exists, and if it does, prevent the pop from happening.
Unfortunately, my cookie is not being set. I've read a few threads about Javascript cookies trying to figure this out. The first thing I found is Chrome does not accept cookies from local files, so I set up an IIS server to host the page.
However, the cookie still is not being set. I read this page to make sure my code was correct, and as far as I can tell, it should be correct.
The code for my page is below. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
var isPopped;
function myFunction() {
alert("Hello! I am an alert box!");
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function pop() {
var queryString = location.search.substring(1); //Get Query String from URL of iFrame source. The substring(1) strips off the ? and only takes the first substring. This can be modified to take more and the resulting string can be edited with Regular Expressions if more flexibility is required.
var urlToPop = "https://www.google.com/#" + queryString //Set URL to pop.
var recentVisitTrue=getCookie("visitRecent");
if (recentVisitTrue != "") {
isPopped = 1;
} else {
window.open(urlToPop,"_blank");
setCookie("visitRecent", "true");
}
}
function setCookie(cName,cValue) {
var date = new Date();
date.setTime(d.getTime() + 8000000);
var expires = "; expires=" + date.toGMTString();
document.cookie = cName + "=" + cValue + expires + ";path=/";
}
function getCookie(cName) {
var name = cName + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</head>
<body onload="pop();">
v0.32
</body>
</html>
Thanks!

Is it possible to automatically log in to link using Javascript

I want to link to a page and when the user clicks on the link his username and password are already there for him. However where i am linking too i don't control that pages code.
Is it possible to have my javascript execute there after the user clicks the link?
$("#link").click(function() {
alert( "Handler for .click() called." );
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("j_username");
var passwordTextBox = document.getElementById("j_password");
usernameTextBox.value = username;
passwordTextBox.value = password;
});
See my JSfiddle
You can't actually execute it from another page, you can however use the following.
The best way to do this is with a cookie, storing the username, and pointing to an encrypted file with an encrypted password. But you can store the encrypted password in a cookie too, as long as it's encrypted before putting it in the cookie.
I originally developed this for a function that will keep a user logged in to a page that redirected to a login whenever it is accessed, it will click the button and bring them to the page after the login page.
working example: Will need to be edited to fit exact elements on any page, and run on the page, probally through a property or permission gained through a download or web app etc.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
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];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function stayLoggedIn() {
setCookie("logged_in","true",30);
setCookie("username", username,30);
setCookie("password",encryptedPassword,30);
return null;
}
window.onload {
var loggedIn = getCookie("logged_in");
if(loggedIn == true) {
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("username");
var passwordTextBox = document.getElementById("password");
//decrypt password here.
usernameTextBox.value = username;
passwordTextBox.value = password;
}
else {}
}
Explained:
first, we set a function to set a cookie and get one, I took these from here
then, I set the function stayLoggedIn() this sets the cookie with the value of "logged_in" to true, so when the user comes to the page, and window.onload runs it's block, the if statement is triggered, and the username and password fields are filled in.
Then, click(element) is called on the logginButton, this can click on php, or html buttons or submit forms etc. This simulates the button being clicked, and the user logging in.
Also: You need to call the function stayLoggedIn() after the link is clicked (like through a google or firefox extension)

javascript delete cookie works bizarre across browser

I'm trying to do a demo test on javascript cookie. Please find the code below which I wrote for testing.
<html>
<head>
<script type='text/javascript' >
function setcookie()
{
alert("check if cookie avail:" +document.cookie.split(';'));
var dt=new Date();
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
alert("now cookie val:" +document.cookie.split(';'));
dt.setDate(dt.getDate()-1);
document.cookie = "expires=" + dt.toUTCString() + ";"
alert("after deletion cookie val:" + document.cookie.split(';'));
}
</script>
</head>
<body>
<input id='txt' onchange='setcookie()' />
</body>
</html>
The code will work as,
Initally, this will display the cookie which is present already in that browser, then I try to set a cookie as 'name=test' with 1day expire time. Using alert I can see the value set in that cookie. In the next line, I try to delete cookie by setting expire date to current date-1. If I use alert to print the cookie value, cookie is displayed with expire date as currentdate-1.
My questions is,
In Mozilla, If I refresh the browser and try to do the same step then the first alert displays the cookie value with expire time as currentdate-1. Why Im getting cookie value even if i delete at the last line of my script. However, once I close the browser the cookie value is empty. Why it is so?
In chrome, If I run the same piece of code, neither of the cookie is set. Why Im not able to set cookie in chrome browsers.
Please tel me why such difference occuring across browsers.
This is not setting the expiry
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
this is
document.cookie='name=test; expires='+dt.toUTCString()+';'
The best is to take well tested cookie code and use that
Try this one or use a jQuery plugin if you use jQuery
// cookie.js file
var daysToKeep = 14; // default cookie life...
var today = new Date();
var expiryDate = new Date(today.getTime() + (daysToKeep * 86400000));
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

Categories