Most efficient way to save JSON data and reuse on next page in JQuery - json

On my (Cordova, jQuery-Mobile) iOS mobile application I receive some JSON values on the first page.
To store them I use arrays.
To pass them and reuse them on the second page I use a each function, count up an integer(i) on every run and push the received data into several arrays, the integer(i) I store in a DIV in data-id. (<div data-id'"+i+"'>)
As soon as the User navigates to the second page by tapping on one of the DIVs I use the integer(i) in data-id to get every value from the arrays and display on page 2.
Example
Database:
ID NAME SURNAME AGE USERID
1 Michael Douglas 44 uid3242
2 Eric Cartman 11 uid9275
3 Felix Woodspuck 38 uid3852
4 Amadeus Mozart 158 uid1120
Script:
ID = [];
NAME = [];
SURNAME = [];
AGE = [];
USERID = [];
for example - If the user clicks on the DIV with data-id=2
iInt = $(this).attr('data-id'); // iInt=2
$("#abc").text(NAME[iInt];) // NAME[2]; --> Eric
$("#xyz").text(SURNAME[iInt];) // SURNAME[2]; --> Cartman
...
This is just an example, please ignore the values.
But in my App I am using a lot of variables on a lot of pages, and it gets a little messy in code, so what I am wondering about is if there is a more efficent way to save the values I get from JSON to use them on the second page? How do you do it?
Thank you.

I've been tucking the JSON string into localstorage, then pulling it out later and restoring to an object.
localStorage.setItem("jsondata",mytextvar);
Then later:
var obj = JSON.parse(localStorage.getItem("jsondata"));

Related

onClick is always returning 25

I'm using reactjs.
I have a series of divs that are created that represent a employee's availability. When clicked, they will display the number. However, they all alert the number 25 instead of their number.
for (
var i = state.availability[day][0];
i <= state.availability[day][1];
i++
) {
tempdaySlot.push(
<div
key={"ena:" + TimeConverter(i)}
style={LocalStyles.daySlot}
onClick={() => alert(i)}
>
{TimeConverter(i)}
</div>
);
}
state.availability is a two dimensional array that holds a number between 1-24 that represents someone's availability (ex [9-17])
TimeConverter is a function that converts a 24 hour type number to the usual 12 hour format (17 = "5 pm")
tempdaySlot is just a temporary array before I put it into a state variable
Use let i instead of var i. var hoists variable to the parent scope, let creates block scope.
this is a hoisting issue, because you defined the i using var it will be hoisted to the top of the function body so the last value which is 25 will be the only thing stored in that variable and since the variable isn't destroyed because it's hoisted it will only show the latest value.
just use let instead of var its a good practice to use let and const instead of var now so try getting used it, it will save you a lot of headaches.
Tl;dr declare i using let, not var
The var keyword creates variables with function scope. However, when you create a closure (like your onClick function), the lexical environment is captured by reference. When you call that onClick function later, it gets the current value of i (which is 25, since that's where the loop stopped), not the value of i when you created the function.
The let keyword creates i with traditional scoping, so in effect a new i is created on each iteration of the loop which solves this problem.
See What's the difference between using "let" and "var"? for more.

Display data from Firebase database in a HTML page

I am new to Firebase and JS.
I am trying to display some user information on a web-page that is stored in Firebase database.
Data format is something as this image:
Based on the image above :
From the available nodes, UserData is the one that holds the name, email, assigned-id
I don't require to show User1/User2/User3, they are unreadable such as HNpTPoCiAYMZsdfdsfDD3SDDSs555S3Bj6X35.
I just need the Values associated with Attr1 and Attr3 for all the users there exists.
Now, I would like to fetch this data and show it in a webpage(one of HTML) in a tabular format.
Name | Assigned ID
___________________
Name 1 | ID 1
Name 1 | ID 2
Name 3 | ID 3
I have seen some tutorials but they weren't clear and helpful.
This is the Javascript code I have written basis some tutorials, and only one record is being displayed from the database, rather than whole -
Also this is the last record available in the database, can i display the same in the sorted order of AssignedID value
(function(){
// Initialize Firebase
var config = {
apiKey: "Aaasff34eaADASDAS334444qSDASD23ASg5H",
authDomain: "APP_NAME.firebaseapp.com",
databaseURL: "https://APP_NAME.firebaseio.com",
storageBucket: "APP-NAME.appspot.com",
messagingSenderId: "51965125444878"
};
firebase.initializeApp(config);
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val(); // childData will be the actual contents of the child
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
document.getElementById("name").innerHTML = name_val;
document.getElementById("id").innerHTML = id_val;
});
});
}());
Can someone kindly help me achieve this? Thanks in advance.
There are two things you need to change 1. instead of using get element by id use jquery and also so that it doesn't overwrite itself use append to list the select items from the database.
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
$("#name").append(name_val);
$("#id").append(id_val);
});
});
This on its own would output your database items one after the other and so to add formatting to every database item you can do things like this (by the way this is why you have to use jquery as this didn't work with the normal js stuff)...
$("#name").append("<p>" + name_val + "</p><p> " + id_val + "</p>
<br>");
This would look like this for every name and id
Name Id
Name Id
Name Id
You could also have used this for entering you data from your database into a table by putting each item in a tag and so on if you don't know what im on about just go learn about html tables and from then on its self-explanatory.
The reason you are only seeing the last item is because of these 2 lines
document.getElementById("name").innerHTML = name_val;
document.getElementById("id").innerHTML = id_val;
You're not creating new items, just writing/overwriting in the same spot. Each item replaces the name/id of the one before until the last item. Consider using element.appendChild() to add the items to an <li> element.
As far as sorting goes, check out this page of the firebase doc: https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
Hope this helps!

How to get data from a specific section in MediaWiki supported wikis

I am parsing a Wikia article and trying to get the data from the right hand side highlighted block, I have already got the left one using the following URL
http://hetalia.wikia.com/api.php?action=parse&prop=revisions&prop=sections&page=America&format=json
But don't know the reference about the right one. What will be the parameter?
The original URL is,
http://hetalia.wikia.com/wiki/America
I believe the only way to get info from the Infoboxes would be to get the page source, which can be done with this query
http://hetalia.wikia.com/api.php?action=query&prop=revisions&rvprop=content&titles=America&format=json
And then parsing the text to get the information, as the source of that box is in this format
{{Character
|name = America
|jname = アメリカ
|image = America0.png
|country = [[wikipedia:United States|The United States of America]]
|human = Alfred F.Jones (アルフレッド・F・ジョーンズ, ''Arufureddo F. Joonzu'')
|age = 19
...
|japanese = [[Katsuyuki Konishi]], Ryoko Shimizu (Young America, drama CD "Prologue"), [[Ai Iwamura]] (Young America, anime), [[Axis Powers Hetalia: The CD|Osamu Ikeda]] (''Flower Of Iris'')
|english = [[Eric Vale]], Stephanie Young (young America)}}
You could use Regex to extract the data from the text, such as using \|age\s*=\s*(\d*) to get the age attribute.

Creating a user generated list in flash

I'm trying to create a flash application that will keep track of user generated values. The app should basically allow the user to input the name of the item and it's cost. The total costs should then be added up to show a total value to the user. I can probably figure out how to add the values together, but I'm not really sure how to allow the user to create a list and then allow the user to save it. Can anyone point me towards a tutorial or point me in the right direction?
I am using variables to add user inputed numbers to come up with a total. The first problem is that actionscript 3.0 does not allow variables for texts. I just converted it to 2.0 to fix this. The second problem, is when I test the app and put in my values and click submit, I get NaN in the total values field. Is there a reason why it wouldn't add the values?
Here is the code I used for the submit button:
on (release) {
total = Number(rent) + Number(food) + Number(travel) + Number(entertainment) + Number(bills);
}
Am I missing anything?
Can I give the input text instance names and then give them variables? How are some ways to go about this?
Thanks for the help!
Have an object array, say for example
var stack:Array = new Array();
Then push the item name and it's cost to that array when user inputs, like
stack.push({item:AAA, cost:xx});
So that you can generate the list whenever you want with that array.
You have to see how this works in code. A list in actionscript could be stored inside an array, vector, dictionary or even an Object.
Var myList:Array = [];
myList.push({name: "item 1", cost: 5 });
myList.push({name: "item 2", cost: 7.5 });
If you want to grab the 'product' of "item 1" from the list, you have to create a function for that, lets call it getProductByName
function getProductByName(name:String):Object
{
for each(var product:Object in myList)
{
if (product.name === name) return product;
}
return null; // no match found
}
You can call that function like this:
var product = getProductByName("item 1");
trace(product.cost); // 5
And you can alter the product, so lets make it more expensive
product.cost += 1;
trace(product.cost); // 6
Have fun! If you are using classes, you would create one for the product, with public name and cost, and in that case you'de better use a vector, to ensure working with the right type.
This is what fixed the issue for me in action script 3.0:
myButton.addEventListener(MouseEvent.CLICK, addThem);
function addThem(e:MouseEvent)
{
totalField.text = String ( Number(field1.text) + Number(field2.text) + ....);
}
I also had to name the instances appropriately.

google visualization api, identify tableid in response function

Hmmm, maybe someone can help me out here or point me in the right direction , as i have been banging my head against the wall for a number of days now and dont seem to be gettin anywhere useful.
(and admittedly i'm pretty new with regards to json,objects, google visulization etc)
essentially, i am running 3 different queries on the same page against 3 different fusion tables, which in return are supposed to return an array of 3 different xets of markers.
all is fine, when i run the queries individually and make an array of the markers .
however, running the 3 queries on the same page, i can't seem to find a way to identify the query in the response function.
any hints much appreciated. and i'll be happy to provide more info if needed (tried to get rid of some unneccessary stuff)
this is what i have. thanks
a) calling the function "setFusionData()" with all relevant vars. something like setFusionData("'LatLng','name'", 2729461);
(this is calles 3 times with different variables)
function setFusionData(selColumns,tableId) {
/****
an actual query example is this:
http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
****/
var query = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq='+ encodeURIComponent("SELECT "+selColumns+" FROM "+tableId+"")
);
query.send(getFusionData); //do something with the response
}
function getFusionData(response) {
/**
here, is the problem as i need to get the table id or reqId or anything that is uniquely passed on from "setFusionData" above
also something like
alert(JSON.stringify(response)) does not return any reqId or table id either
***/
/*return rows/columns and add values to an array of markers***/
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
for (i = 0; i < numRows; i++) {
/* add markers to array etc this works fine***/
}
}
i also tried something like this:
function setFusionData(selColumns,tableId) {
......
query.send(getFusionData({reqId:tableId}));
}
function getFusionData(response) {
alert(response['reqId']);//returns tableId. but how do i get the tableData ?
}
with wich i can get the reqId, but not the table*Data*. So I am only able to get either id or data :(
----edit----------------
after messing around a bit more (see below) it appears that the key/value pairs that get returned when typing the query into the browser directly are different than what gets returned by the call from the script...i.e the following
http ://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
typed directly into the browser bar will return
version:'0.5',reqId:'1234',status:'ok',table etc
however, calling the same from within the script returns something like
{
"rj":"0.5","ef":"ok","pb":[],"qb":[],"h":"{"cols":
[{"id":"col2","label":"LatLng","type":"string"},{"id":"col1","label":"name","type":"string"}],
"rows":
[{"c":[{"v":"47.20572,12.70414"},
{"v":"Hohe Tauern"}]},{"c":[{"v":"47.5530395,12.925611"},{"v":"Berchtesgaden"}]},{"c":[{"v":"47.5585405,14.61887"},{"v":"Gesu00e4use"}]}],
"p":{"totalrows":3}
}"
}
, so no 'reqId' but only some cryptic keys (without one that looks like the reqId either)...... anyone any idea why that would/could be ?
Sometimes you can figure it out by just looking at the JSON response, your sample request returns:
google.visualization.Query.setResponse({
version:'0.5',
reqId:'1234',
status:'ok',
table: {
...
}
})
You already got response.reqId to identify which request is this the response for, now you can use response.table to create a new DataTable instance:
var dt = new google.visualization.DataTable(response.table);
Or, since you have multiple tables, put then in an array indexed with the reqId
tables[response.reqId] = new google.visualization.DataTable(response.table);
You'd do var tables = new Array() before calling setFusionData() for the first time.