Use cookie to set link? - javascript

If cookies are used to stor simple strings can I also use the cookie to set the link of a button.
the idea: I have a simple HTML which i use to create a help file (this is very simple and I already have it), but we also make use of heaps of relating MSDS documents, so instead of me finding the thousands of documents online, i was thinking that Id get my users to set this by setting a cookie and ussing the cookies string to set the link ready for use the next time?
I can set read delete and modyfy cookies using Javascript...

Granted this function (http://www.w3schools.com/js/js_cookies.asp) to get the cookie item works, this should do the job:
var getCookie = function(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var click = function () {
window.location.href = getCookie('buttonUrl');
}
<button onclick="click()">See documentation</button>

Related

How to get the data inside the XML

I have this response data from the server that I authenticate.
<session session-guid="D39C1215-2F31-8641-E5T2-C7G35RT69127" user-id="34"> </session>
How can I get the value of session-guid and user-id and store them into 1 variable for each.
Thank you.
In plain Javascript in a modern browser you can use document.querySelectorAll().
For example, assuming you only have one session tag:
var session = document.querySelectorAll("session")[0];
var session_guid = session.getAttribute("session-guid");
var user_id = session.getAttribute("user-id");
console.log("session-guid: " + session_guid);
console.log("user-id: " + user_id);
If you have more that one session tag you can use forEach on the results of querySelectorAll() to locate the one you want. If you know that you're only going to have one session element you can use document.querySelector() instead of document.querySelectorAll()[0].
Here is one way to get the values client side. For this method you will need to add any custom class to your element like below:
Now write below lines of code inside tag:
var $mySession = jQuery(document.getElementsByClassName("mySession"));
for (i = 0; i < $mySession.length; i++) {
var sessionguid = jQuery($mySession[i]).attr('session-guid');
var userid = jQuery($mySession[i]).attr('user-id');
console.log(sessionguid);
console.log(userid);
}
You can check the values of "sessionguid" and "userid" variable in your browser console.
Here is what you can do to get the required data from the XML.
function getXMLData(xml) {
var txt, xmlDoc;
//get the responseXML
xmlDoc = xml.responseXML;
txt = "";
//get all the session nodes
var sessions = xmlDoc.getElementsByTagName("session");//this returns a array of nodes
for(var i =0;i<sessions.length;i++){
//iterate over nodes and get the attributes
txt += sessions[i].getAttribute("session-guid")+"<br />";
}
document.getElementById("demo").innerHTML = txt;
}
this function accepts the response as a parameter. And then extracts out the sessions nodes and the required attribute. You can modify it according to your requirements.
Here is a PLNKR demo for the same

how to get single value by cookie in java script

java script code is store cookie
document.cookie = 'CookieName='+'grid';
i want to get CookieName value grid i haveto store many cookie but i get this one this cookie store at the first index in cookie
$( document ).ready(function() {
var CookieName=document.cookie;
if(CookieName =='grid')
{
$('#tab_b').hide();
$('#tab_a').show();
}
else {
$('#tab_a').hide();
$('#tab_b').show();
}
});
how to get CookieName value
I got the impression that you found the answer by Jay Blanchard too long, so I'll provide a shorter alternative. But first let me say something else. As a comment to Jay Blanchard's answer, you wrote:
thanks bro i have got it and very simple and short function check it var allcookies = document.cookie; cookiearray = allcookies.split(';'); name = cookiearray[0].split('=')[0]; value = cookiearray[0].split('=')[1];
However, I highly recommend you rethink that as this assumes CookieName is always the first cookie. (Someone might say "but I will somehow make sure it always is", but the point is, this is key/value, not array, so the approach is conceptually wrong and confusing, or as they say, bad practice).
Now, for the code:
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)CookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1");
This is something I have blantantly stolen from the MDN page on cookies which I highly recommend if you want to learn more about cookies.
I have written a small function (I could probably make this much more efficient, but I have used it for a long time) which should work for you:
function getCookieAttr(attribute) {
var attr = attribute + "="; // create an attribute string
var parts = document.cookie.split(';'); // split the cookie into parts
for(var i = 0; i <parts.length; i++) { // loop through the parts for each item
var item = parts[i];
while (item.charAt(0)==' ') { // account for spaces in the cookie
item = item.substring(1); // set the item
}
if (item.indexOf(attr) == 0) { // if the item matches the attribute
return item.substring(attr.length,item.length); // return the value
}
}
return "";
}
To use the function pass the attribute name:
document.cookie = "CookieName=grid";
console.log(getCookieAttr('CookieName'));

sending stored javascript variables using href to a new url

Im trying to get a stored variable that came in a url to be used as a variable with href.
The code I have so far is:
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
And this works
http://www.somesite.com/?title=1254&keyphrase=phase1
arrives to the page with the script and it does store the values for title and keyphrase.
What Im trying to do is to build a href that in the end has a link like this:
http://www.anewsite.com/1254/
The domain will never change - only the variable at the end.
Is this possible ?
Any help will be most appreciated.

Google Script to see if text contains a value

I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');

Can't access fields of a Javascript Object

The following Javascript function returns a JS object:
function getCookies() {
var result = {};
var cookie = {};
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
cookie = cookies[i].split('=');
result[cookie[0]] = cookie[1];
}
return result;
}
When I tried to access its fields the "easy" way, all I got was "undefined", eg:
var c = getCookies();
alert(c.a_cookie_name);
alert(c['a_cookie_name']);
The only way I could access the keys and values was iterating through the fields, eg:
for(cookieName in c){
alert(c[cookieName]);
}
The question is how to access the fields without iterating?
Thank you.
P.S. The keys and values do exist, I can see the object fields with console.log(getCookies()) in Chrome.
You are properly accessing fields the problem is that hte fields you're accessing don't exist. It' looks like the property named a_cookie_name simply doesn't exist on the object.
EDIT
Given that the Chrome console shows the properties as existing, one possibility to consider is there is white space in the names of the properties. This could explain the difference as the white space would be hard to see in the console. To test that out try the following. It will make the spaces a bit more visible if they are there
for (var cookieName in c) {
alert('"' + cookieName + '"="' + c[cookieName] + '"');
}

Categories