Javascript getting Cookie won't do on certain value - javascript

I have this function in my PHP :
setcookie("UserPusser", $user, time() + 604800, "/pusser/beta/");
setcookie("PassPusser", $pass, time() + 604800, "/pusser/beta/");
setcookie("NotifPusser", $notif, time() + 604800, "/pusser/beta/");
And I have this function in my javascript
function getThisCookie(name){
var value;
var singleCookie = document.cookie.split(";")
for(var x in singleCookie){
var y = singleCookie[x].split("=");
if(y[0] == name) {
value = y[1];
}
}
return value;
}
When I type alert(getThisCookie('UserPusser')) the result is what I want. But when I tried to write alert(getThisCookie('NotifPusser')); or alert(getThisCookie('PassPusser')); the result is : undefined.
Anyone can help me?
What I'm trying to do is make the browser remember the value of checkbox each time the page reload.

Just for completeness a full answer here instead of only the hint within the comments:
Cookie values are separated by ; (semicolon + whitespace)
This leaves you with something like this:
cookie = 'a=123; b=456; c=678'
In order to separate them you have to split them by the same delimiter.
With modern browsers (JS 1.6+ I guess, not quite sure right now) or libraries like underscore.js you could as well put them into an object.
// if your browser supports 'reduce'
var cookieObject = document.cookie.split('; ').reduce(function(o, kvp) {
var split_kvp = kvp.split('=');
o[split_kvp[0]] = split_kvp[1];
return o;
}, {});
// underscore.js version
var cookieObject = _.reduce(document.cookie.split('; '), function(o, kvp) {
var split_kvp = kvp.split('=');
o[split_kvp[0]] = split_kvp[1];
return o;
}, {});
Anyway after performing any of those you can easily access the values you are looking for:
cookieObject.a == 123
cookieObject.b == 456
Just remember that those are readOnly. In order to modify them you'd have to write the object back to the document.cookie
// again, modern browser version
document.cookie = Object.keys(cookieObject).map(function(key) {
return key + '=' + cookieObject[key];
}).join('; ');
// with underscore.js
document.cookie = _.chain(cookieObject).keys().map(function(key) {
return key + '=' + cookieObject[key];
}).value().join('; ')

Related

The function to set many cookies at one time doesn't work

I want to set cookies. I have an array and a function setCookies. In this function, I loop through myCookies array and after some manipulation I get a string. This string supposed to set cookies.
const myCookies =
[
{budgetMonth: someValue1},
{budgetDay: someValue2},
{expensesMonth: someValue3}
];
function setCookies(myCookies) {
let arr = [];
for(let i of Object.keys(myCookies)) {
let myItems = myCookies[i];
for(let y of Object.keys(myItems)) {
arr.push('document.cookie ' + '= "' + y + '=' + myItems[y] + "\"");
}
}
let stri = '';
arr.forEach(item => {
stri += item + ';'
});
return stri;
}
setCookies(myCookies);
When I log stri I see the strings listed below. Isn't it a right way to set cookie? I guess it is, but why it doesn't work? When I just type in my code document.cookie = "budgetMonth=someValue1" the cookie is set.
document.cookie = "budgetMonth=someValue1";
document.cookie = "budgetDay=someValue2";
document.cookie = "expensesMonth=someValue3";
There are several issues with your code.
the structure in which you are storing the values for the cookies is not necessarily incorrect, but writing it as myCookies = {name1: value1, name2: value2} simplifies your code, indirectly verifies if you aren't setting the same cookie name multiple times (unless you really want to do that, setting multiple paths, for the same key, for example), and allows you to add/remove a cookie from the list later on in your code in a much more simplified way;
you are generating an array, and with that array, a string, but you aren't doing anything with any of them. To actually set up the cookie, you have to execute the code document.cookie = something.
A very simplified version of your code (untested) would be something like:
const myCookies = {
budgetMonth: someValue1,
budgetDay: someValue2,
expensesMonth: someValue3
};
function setCookies(myCookies) {
for(let k of Object.keys(myCookies)) {
document.cookie = k + "=" + myCookies[k];
}
}
setCookies(myCookies);

Javascript Eval to work for both function and plain string

I want to display a list of items, now sometimes these items' title will just be a plain string, and sometimes it might be a value returned by a function.
How can I make both events work using eval() ?
Here is an example code:
var a1 = "formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')"
var a2 = "#america"
var result1 = eval(a1) // works well!
var result2 = eval(a2) // doesn't work, need to use eval('a2') but then first one doesn't work
Only thing I can think of is when creating the string for example "#america" have it saved like "'#america'" instead, but I would rather avoid it
[edit]
Eventually I will have something like this:
arr.push("formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')");
arr.push("#america");
for(var i = 0; i < arr.length; i++) {
var ev = eval(arr[i]);
console.log(ev);
}
What I would suggest is wrapping the eval in a try catch block, if the eval succeeds then return the value otherwise return the value originally passed to function. There are many cases where eval can fail as it is simply trying to parse the string as valid JavaScript so any invalid JS not just a simple string can cause it to fail so its better to be safe and catch any error that comes out of it.
var evaluate = function(value) {
try {
return eval(value);
}
catch(err)
{
return value;
}
}
var ev = eval(a2) would be equivalent to var ev = eval('#america') which doesn't make any real sense.
When you say eval('a2') works, I assume that ev = '#america' is the desired outcome. The 'a2' expression is evaluated as simply accessing the value of the variable of that name.
You're basically just having a series of strings that may be valid javascript code, or may not, and there's no way to tell which is which. In that case, the best you can do is something like
try {
ev = eval(arr[i]);
} catch(ex) {
ev = arr[i];
}
... which obviously looks terrible. Can you control the content of the entries in arr?
arr.push(function() {
return formatDate(startTime) - formatDate(endTime);
});
arr.push("#america");
In that case, you could check for the type of each entry, and act on it accordingly:
for(var i = 0; i < arr.length; i++) {
var ev = typeof arr[i] == 'function' ? arr[i]() : arr[i];
console.log(ev);
}
this is that i should do:
var a1 = function(){
return formatDate(startTime) + formatDate(endTime)
}
var a2 = "#america"
var result1 = a1();
var result2 = a2;
Yo can check with typeof(a1) if the var is a function or an object or anyting else.
if(typeof(a1)=='function'){
result = a1();
}else{
result=a1;
}

Send #Model variable as parameter to a JavaScript function

start reading at 'UPDATE'
I have a JavaScript function :
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
And I have the following field that has to be changed when I change another value:
<span id="amount"></span>
When I change a value in this textbox the above field should be updated:
#Html.TextBoxFor(model => model.TimeAndMaterialsRate, new { onkeyup = "getAmount()" })
This code works fine as long as I do not try to send any parameters in getAmount(), but I can't seem to figure out how to get it to work, could anyone please help me?
This is one of the things that I tried
new { onkeyup = "getAmount("
+ #Model.AdminFee + ","
+ #Model.TimeAndMaterialsRate + ","
+ #Model.TotalTimeSpent.Hours + ","
+ #Model.MinimumCharge + ")"
}
I also tried to above without '#'s
UPDATE:
The above code works now although it seems the function doesn't work properly.
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
The values passed into the function are id, id, double, id. Any clue on why this doesn't work?
I think your problem is a slight syntax error with the end of your string. The last plus sign is in the wrong place. It should be like this:
new { onkeyup = "getAmount("+#Model.AdminFee+","+#Model.TimeAndMaterialsRate+","+#Model.TotalTimeSpent+","+#Model.MinimumCharge+")" })
I'd say to use eval, but it's preety bad practice because it can be really injected & stuff.
Look at this article http://www.sitepoint.com/call-javascript-function-string-without-using-eval/
What you need is :
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);
Your params will look like :
var fnparams = {
minimumCharge : '#Model.MinimumCharge',
... // and so on
};
And you will get them in this way :
parseInt(fnparams.minimumCharge);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Get query string parameters url values with jQuery / Javascript (querystring)

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:
$('?search').val();
Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.
I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.
After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
//Assuming URL has "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?
post=1234&action=edit&active=1"
UPDATE : IE is not supported
use this function from an answer below instead of URLSearchParams
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('action')); //edit
Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):
location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
if (pair === "") return;
var parts = pair.split("=");
location.queryString[parts[0]] = parts[1] &&
decodeURIComponent(parts[1].replace(/\+/g, " "));
});
http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.
JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use
$.url().param('search');
This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.
Or you can use js-url instead. Its quite similar to the one below.
So you can access the query param like $.url('?search')
Found this gem from our friends over at SitePoint.
https://www.sitepoint.com/url-parameters-jquery/.
Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.
//URL is http://www.example.com/mypage?ref=registration&email=bobo#example.com
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //bobo#example.com
Use as you will.
This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');
I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:
function getParameterByName( name ){
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp( regexS ),
results = regex.exec( window.location.search );
if( results == null ){
return "";
} else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
// example caller:
var result = getParameterByName('Mode');
Building on #Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).
function parseQueryString () {
var parsedParameters = {},
uriParameters = location.search.substr(1).split('&');
for (var i = 0; i < uriParameters.length; i++) {
var parameter = uriParameters[i].split('=');
parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
}
return parsedParameters;
}
function parseQueryString(queryString) {
if (!queryString) {
return false;
}
let queries = queryString.split("&"), params = {}, temp;
for (let i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
if (temp[1] !== '') {
params[temp[0]] = temp[1];
}
}
return params;
}
I use this.
Written in Vanilla Javascript
//Get URL
var loc = window.location.href;
console.log(loc);
var index = loc.indexOf("?");
console.log(loc.substr(index+1));
var splitted = loc.substr(index+1).split('&');
console.log(splitted);
var paramObj = [];
for(var i=0;i<splitted.length;i++){
var params = splitted[i].split('=');
var key = params[0];
var value = params[1];
var obj = {
[key] : value
};
paramObj.push(obj);
}
console.log(paramObj);
//Loop through paramObj to get all the params in query string.
function getQueryStringValue(uri, key) {
var regEx = new RegExp("[\\?&]" + key + "=([^&#]*)");
var matches = uri.match(regEx);
return matches == null ? null : matches[1];
}
function testQueryString(){
var uri = document.getElementById("uri").value;
var searchKey = document.getElementById("searchKey").value;
var result = getQueryStringValue(uri, searchKey);
document.getElementById("result").value = result;
}
<input type="text" id="uri" placeholder="Uri"/>
<input type="text" id="searchKey" placeholder="Search Key"/>
<Button onclick="testQueryString()">Run</Button><br/>
<input type="text" id="result" disabled placeholder="Result"/>

Categories

Resources