why are my javascript floating point numbers getting sliced up? - javascript

I have an array filled with latitude and longitude pairs pushed like this
doneDotsA.push(lat+"|"+lon);
the values can look like 51.5 or -0.11666666666666667, etc.
then the array is stored in a cookie as an array.
when I try to read the cookie contents it looks like this when In examine it
alert('doneDotsA='+doneDotsA.toString());
yields results like this:
doneDotsA=51.5|-0.11666666666666667
so far so good. however when I try to extract the values like this
for (var t = 0; t < doneDotsA.length; t++) {
alert('val='+doneDotsA[t]);
}
the alert shows 'val=5' then 'val=1' then 'val=.' then 'val=5' etc. somehow reading only one character at a time instead of returning the full number as I'd expect it to do.
does saving an array into a cookie do something to the numbers?
any ideas?

stored in a cookie as an array
Cookies are always stored and retrieved as a string, unless you use custom code to rebuild it into an array after the fact.

A solution like this could be to take your latitude and longitude and put them into a JSON object for serialization and storage in the cookie. Then you can parse them into objects when the site loads.
var coords = {
points:[
{lat:12.4444446,lon:44.55555},
{lat:12.4444446,lon:44.55555}
]
};
var serialized = JSON.stringify(coords);
toStore(serialized);
Then you can just set it to local store or to anyplace you can store a string.
var myLoaded = fromStore();
var coords = JSON.parse(myLoaded);
coords.points.each(function(coord) {
// do something with points.
});
You should then be able to do something with the points you saved.
One note: you might want to check that myLoaded is not an empty string or wrap parse in a try/catch block. A poorly formed structure will throw an exception.

Related

Storing and returning values in an Array using jQuery Cookies

I'm attempting to create a 'document bank' where the user can save documents and then download as a batch of files. The Cookies seems to be saving the array values, but I'm having trouble figuring out how to return the length of the stored array as well as how to loop through all of the values stored within it.
Here's what I have going on so far:
$('.btn-save').click(function(e){
e.preventDefault();
counter++;
$('.doc-counter').text(counter);
var docVal = $(this).data('url');
docArray.push(docVal);
Cookies.set('docBank', docArray, {
expires: 1
});
Cookies.set('docCount', $('.doc-counter').text(counter), {
expires: 1
});
});
console.log(Cookies.get('docBank'));
What I'm trying to achieve is:
Store all data attributes (file URLs) into an array
Store all values in the array using Cookies
Get count of stored values in array
Loop through values of stored array and eventually spit out file downloads
console.log(Cookies.get('docBank').length); doesn't seem to be doing the trick for returning the total array size.
Any guidance on this would be appreciated! I'm pretty sure there's a simple solution to this that I'm not seeing.
Thanks!
You have to use the Cookies.getJSON method to get the array, otherwise you will get only the array as a JSON string.
console.log(Cookies.getJSON('docBank').length);

Javascript How to write localStorage script

How to write localStorage script which will remember the value of turning odometer...so that each time the user visits the site again , the odometer will resume on the value on which odometer was at when the user left the site? I'm beginner in javascript so please understand...
This is my code: https://jsfiddle.net/aht87opr/17/
I've found the following code which might help with my case: http://jsfiddle.net/Jonathan_Ironman/Hn7jc/
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Nicely done on the odometer, looks good. Local storage is simple.
To set local storage:
localStorage.setItem("key", "value");
To get local storage:
var number = localStorage.getItem("key");
Be sure to try getting the local storage first so you can handle any null errors.
Get and Set
localStorage has a few ways to get and set values to the browser. The simplest is treating it like a regular object.
localStorage.distance = 55;
you can then retrieve the value by accessing the property name you created earlier.
console.log(localStorage.distance); // "55"
Strings are stored, parse the string
Notice that localStorage.distance was set as a number but when accessed was a string. If you only need to store a number you could pass the string through a function like parseInt().
console.log(parseInt(localStorage.distance)); // 55
Another solution is to use JSON
create an object model of your odometer.
var odometer = { distance: 55, timeForOilChange: false };
Then write to the localStorage passing your model through JSON.stringify
localStorage.odometer = JSON.stringify(odometer);
and read the value back out using JSON.parse
console.log(JSON.parse(localStorage.odometer));
// { distance: 55, timeForOilChange: false }

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

How do I use #DbLookup results to populate a Readers field in xpages?

db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)

JSON Data format

Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();

Categories