Hi guys can How to assign $_GET value to a variable using pure JavaScript I have HTML structure not php
You could do something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length;
key += '=';
while (i-- > 0) {
if (params[i].lastIndexOf(key, 0) === 0)
return params[i].slice(key.length);
}
return false;
}
You may also want to consider if you want to use decodeURIComponent on these values as they may be URI encoded
If you want to also permit keys to be URI encoded then this method starts to have issues and you would have to create an Object mapping, which would look something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length,
j,
o = Object.create(null);
for (i = 0; i < params.length; ++i) {
j = params[i].indexOf('=');
if (j === -1) // how do you want to treat found but no value?
o[decodeURIComponent(params[i])] = null;
else
o[decodeURIComponent(params[i].slice(0, j))] = decodeURIComponent(params[i].slice(j + 1));
}
if (key in o) return o[key];
return false; // how do you wan to treat not found?
}
You could also create and cache this Object in advance instead of generating it for each invocation
combine the php code and javascript code !
var x=<?php echo $_GET['whatever'];?>;
so first the php code is being executed server-side and then it's result in html is assigned to a variable in javascript ...
(Apologies if a similar question has been asked, I could not find it)
Basically I have a JSON object with around 10 properties (fixed amount) that contains personal settings for an app without a user system and I would like users to be able to obtain a code that converts to that object with the proper values for each property. That way, they would be able to access the app with their settings using a permalink.
Question is: Is there a method or a specific indicated technique to transform JSON serialized objects (i.e. JSON string) into numbers, or an hexadecimal code? I've seen several websites do a similar thing from a user point of view.
My approach since I have a finite set of properties and possible values would be to hardcode the string (e.g. if property 1 has value x, first char in string is 1, if it has value y, then it's 2, etc...) but I'm wondering if there is anything best suited for that kind of thing.
Lets do this.
setup is object I used for testing
var setup = { "abc" : "asdasd",
"special" : "my wife hates me",
"Kids" : 7564
};
function to generate link:
function generateLinkWithSpecialSetup(setup) {
var str = JSON.stringify(setup);
var hash = "";
for(var i =0; i<str.length;i++) {
hash += str.charCodeAt(i).toString(16);
}
return "example.com/special-setup/#" + hash;
}
functions to find setup from hash:
function findSetupFromHash() {
var hash = window.location.hash.substring(1);
var str = hex2a(hash);
return JSON.parse(str);
}
function hex2a(hexx) {
var hex = hexx.toString(); //force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
I have to save in a cookie a small amount of data.
Would be wonderful if javascript (natively) provide a way to serialize/deserialize an array (or an object).
To be honest, I have tried to write my own piece of code, it is based on the idea that we could serialize an array recursively converting it in a key/value querystring and viceversa.
Well, this is the code:
var lib = {
serialize : function(_a) {
var s = '', enc = encodeURIComponent;
for (var k in _a) {
if (s) s += '&';
s += enc(k) + '=' + ((typeof _a[k] == 'object') ? '?'+enc(lib.serialize(_a[k])) : enc(_a[k]));
}
return s;
},
deserialize : function(_s) {
var a = [], dec = decodeURIComponent;
var list = _s.split('&');
for (var c in list) {
var kv = list[c].split('=');
var v = kv[1].split('?');
kv[1] = (v.length > 1) ? lib.deserialize(dec(v[1])) : dec(kv[1]);
a[dec(kv[0])] = kv[1];
}
return a;
}
};
http://jsfiddle.net/P7wT8/
Although it seems to works quite fine, could someone suggest me something of better and shorter?
A piece of code or a library, something of little and easy to implement Javascript array serialize/deserialize ?
I think your best approach is to use JSON.
JSON.stringify and JSON.parse can encode and decode the values.
JSON is a standard format nowadays, so it is clearer to other developers what's happening.
The only limitation is that IE 7 and below do not support JSON functions natively and require a library.
I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.
I'm currently using javascript eval() to check and create a multidimensional object that I have no idea of the depth.
Basically, I want to know if there's any way to create this multi-depth object. The object can be as deep as result['one']['two']['three']['four']['five']['six']['seven']. I know there are cases where using eval() is perfectly fine, but I'm also worried about performance. I thought about referencing each depth to a new variable, but I don't know how to do pointers in Javascript
create = function(fields, create_array){
var field;
for (j = 0; j < len; j++){
field = fields.slice(0, j).join('');
if (field){
// is there any way to do this without eval?
eval('if (typeof result' + field + ' == "undefined" || !result' + field + ') result' + field + ' = ' + (create_array?'[]':'{}') + ';');
}
}
}
How about
var deep = { one: { two: { three: { four: { five: { six: { seven: 'peek-a-boo!' }}}}}}};
I don't see what "eval()" has to do with this at all; there's no reason to "initialize" such an object. Just create them.
If you wanted to write a function with an API like you've got (for reasons I don't understand), you could do this:
function create(fields, create_array) {
var rv = create_array ? [] : {}, o = rv;
for (var i = 0; i < fields.length; ++i) {
o = o[fields[i]] = create_array ? [] : {};
}
return rv;
}
There doesn't seem to be any point to the "create_array" flag, since you're presumably always using strings for keys.
Never mind, found my way in. I used a recursive function to ensure that the object was created properly.
create = function(create_array, res, path){
var field = fields.shift();
if (field){
if (typeof res[field] == "undefined" || !res[field]) res[field] = (create_array?[]:{});
path.push('["' + field + '"]');
create(create_array, res[field], path);
}
}
var result = {}, strpath = [], fields[];
create(true, result, strpath);
eval('result' + strpath.join('') + ' = value;');
being variable "field" a variable outside the function, that contained the levels of the object. doing result["field"]["name"]["first"] = value without the ["field"] or ["name"] field existing or defined as an object, would throw an error and stop execution, that's why I'm pre-creating the object variable, either as an array or object.
I couldn't find another option for the second eval() though. There's no way to provide a way to access multiple properties on an object without knowing the depth.