When I try to read my cookie that I have set something does not seem right
Here is my cookie functions
function readCookie(){
if (document.cookie !=""){
document.getElementsByName("eMail").innerHTML = alert("hello, " +
document.cookie.split("=")[1]);
}
}
//for setting cookies
function writeCookie(cName, cValue, expDate, cPath, cDomain, cSecure){
if(cName && cValue!= ""){
var cString = cName + " = " + escape(cValue);
if (expDate) cString += ";expires=" + expDate,toGMString();
if (cPath) cString += ";path=" + cPath;
if (cDomain) cString += ";domain=" + cDomain;
if (cSecure) cString += ";secure";
document.cookie = cString;
}
}
cookie being set
<input type="submit" value="Submit"
onclick="writeCookie('userId',document.getElementsByName('eMail').value)"/>
alert box
hello, undefined;__utma
thought on what this means?
The alert function returns undefined
So
document.getElementsByName("eMail").innerHTML = alert("hello, " +
document.cookie.split("=")[1]);
Is setting the html of eMail to undefined.
Also, getElementsByName returns a collection of elements.
Did you mean
document.getElementsByName("eMail")[0].innerHTML = "hello, " +
document.cookie.split("=")[1];
Or are there multiple elements with this name?
var eMailElements = document.getElementsByName("eMail");
for (var i = 0; i < eMailElements.length; i++)
eMailElements[i].innerHTML = "hello, " + document.cookie.split("=")[1];
Finally, if there's only one element you're targeting, you can give it a (unique) id, then simply do
document.getElementById("eMailId").innerHTML = "hello, " +
document.cookie.split("=")[1];
A few problems:
if(cName && cValue!= ""){
Change it to this:
if ((cName != "") && (cValue != "")) {
Also this line has a problem:
if (expDate) cString += ";expires=" + expDate,toGMString();
^ Should be a period
I see __utma in there which tells me one thing: You have Google ads somewhere on the page. They set cookies for tracking users, and your script is reading them. Your method of reading cookies is wrong anyway.
function readCookie(cName) {
var cookies = document.cookie.split(";"),
l = cookies.length, i, k, v;
for( i=0; i<l; i++) {
v = cookies[i].split("=");
k = v.shift();
v = v.join("=");
if( k == cName) return v;
}
}
Also, getElementsByName() returns a NodeList, so you need to get [0] off of it, or use getElementById() instead when writing the cookie - this is why the cookie result is undefined.
Related
I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.
What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.
function getTempDev(devNumTemp, devNumHum, id, description){
$.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
var array = result.Device_Num_42.states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
$("#id").html(description + "<div class='right'>" + array[i].value + "°C" + " (" + someVariable + "%" + ")" + "<br></div>");
}
}
};
objectFindByKey(array, 'service', 'something');
});
};
You can acces to object's properties like this
var array = result["Device_Num_" + devNumTemp].states;
It's considered a good practice to test for field's existance before trying to access it:
var array = [];
if (result && result["Device_Num_" + devNumTemp]){
array = result["Device_Num_" + devNumTemp].states;
}
This way we prevent Null Pointer Exception type errors.
now when I put my own Object in alert function I see
[Object object]
that is pointless information. is there any way using reflection to get all fields and values of those fields?
JSON.stringify is often times builtin and can serialize most objects you pass to it.
That said, you should probably just use a debugger or console.log instead of alert-ing things.
Here is one of many. But better to use console.log() then alert
function objectToString(o){
var parse = function(_o){
var a = [], t;
for(var p in _o){
if(_o.hasOwnProperty(p)){
t = _o[p];
if(t && typeof t == "object"){
a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
}
else {
if(typeof t == "string"){
a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
}
else{
a[a.length] = [ p+ ": " + t.toString()];
}
}
}
}
return a;
}
return "{" + parse(o).join(", ") + "}";
}
sure, maybe something like
function alertObject(0){
var str = "";
for(i in o)
str += i + " " + o[i] + "\n";
alert(str);
}
Edit :: Note this is just a silly little example.
so I'm parsing through a JSON object like so
if(val.function1!==""){
$("#contentFunction").text(val.function1);
}
if(val.function2!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2);
}
if(val.function3!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2
+ "; " + val.function3);
}
I'm wondiering if there is a better way of checking if my json object property is empty instead of having tons of conditions... this gets really messy if for instance I have up to val.function10
Thanks for your help
var strs = [];
for (var i = 0; i < 10; i++) {
var value = val["function" + i];
value && strs.push(value);
}
$("#contentFunction").text(strs.join("; "));
Something like this?
var content = "";
for (var prop in val) {
if (!val.hasOwnProperty(prop)) continue;
if (val[prop] !== "") {
content += "; " + val[prop];
}
}
Or in node.js (or modern browsers):
var c = Object.keys(val).filter(function (k) {
return val[k] !== "";
}).map(function (k) {
return val[k];
}).join("; ");
A tool like underscorejs will help you enumerate functions and properties.
I want to convert a JSON object to a XML String and I can't figure a proper way to do it.
I've found a neat little jQuery plugin called json2xml at https://gist.github.com/c4milo/3738875 but it doesn't escape the data.
How can I escape the data properly so that the browser's XML parser will work?
You can try this small library http://code.google.com/p/x2js/
There is no unique way of doing this. You should be using XML with a schema only, and JSON doesn't have such a schema. Any such transformation when done naively is likely to break.
Why don't you just use XML or JSON consequently?
You can use the external js available by google named x2js.js
You can see the demo over here.
jsFiddle Demo
you can use this function in your code to convert JSON to XML in js
var json2xml = function (o) {
var tab = "\t";
var toXml = function (v, name, ind) {
var xml = "";
if (v instanceof Array) {
for (var i = 0, n = v.length; i < n; i++)
xml += ind + toXml(v[i], name, ind + "\t") + "\n";
}
else if (typeof (v) == "object") {
var hasChild = false;
xml += ind + "<" + name;
for (var m in v) {
if (m.charAt(0) == "#")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "#")
xml += toXml(v[m], m, ind + "\t");
}
xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
}
}
else {
xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
}
}
return xml;
};
you get XML DOM in return, which in return you need to serialize
so in the main
var xmlDOM = json2xml(eval(jsonObj));
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(xmlDOM);
I am using the eBay JavaScript Finding API. The currency id member of the findItemsAdvancedResponse object is defined as #currencyId. So I am retrieving this value as:
function _cb_findItemsAdvanced(root) {
var items = root.findItemsAdvancedResponse[0].searchResult[0].item || [];
var html = [];
if (items.length == 0) {
html.push('No Results');
}
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var price = Number(item.sellingStatus[0].currentPrice[0].`__value__`).toFixed(2);
var currency = ""
var currency = item.sellingStatus[0].currentPrice[0].#currencyId;
if (null != title && null != viewitem) {
html.push('<div class="item-layout5"><table><tr><td><div style="width:102px;overflow:hidden;">');
html.push('<img src="' + pic + '" border= "" alt="' + title + '" /></div></td>');
html.push('<td><span class="itemname">' + title + '</span></td></tr>');
html.push('<tr><td><img src="PTMFOG0000000064.gif" alt="" /></td><td><span class="buyprice">' + currency + ' $' + price + '</span></td></tr></table></div>');
}
}
document.getElementById("results").innerHTML = html.join("");
} // End _cb_findItemsByKeywords() function
This works fine for Firefox browsers, but not for Google Chrome or IE (I get a compilation error).
Is using the # symbol in a member name acceptable in JavaScript? And what workaround can I use so that the above code will work in all browsers?
Thanks
In javascript, the syntax
foo.bar
is equivalent to
foo['bar']
and the latter works even when 'bar' is not a valid identifier name, as in this case.