Passing Local storage data betwen pages using jquery - html

I have array in my main.js page and I store that data in local storage using
//main page
$j.each(response.records, function(i, record) {
localStorage['sizes']=JSON.stringify(response.totalSize);
var names=[];
names[0]=getDate(record.StartDateTime);
localStorage['names']=JSON.stringify(names);
window.location = "theme.html";
});
//next page
var size = JSON.parse(localStorage['sizes']);
alert("Size in next page" + size);
for(var i=0;i<size;i++)
{
var storedNames = [];
storedNames=JSON.parse(localStorage['names']);
alert("Stored Array value " + storedNames);
}
record contain all data like date, time,location etc. I want to send complete record in next page, but in that page I am not able to parse that object. So I decided to send only date, but here count of date is 4, but in another page I got only last date store in array. So I store length of response in main page and fetch size in next page and after that loop is running, but again I got the same last value 4 times.
Please help me.
Thanks in advance

Try this:
//main page
var names=[];
$.each(response.records, function(i, record) {
names[i]=getDate(record.StartDateTime);
});
localStorage['names']=JSON.stringify(names);
window.location = "theme.html";
//next page
var storedNames=JSON.parse(localStorage['names']), allElements = [];
$.each(storedNames, function(i, el) {
allElements[i] = el;
});
alert("Stored Array value " + allElements);

Related

How to 'merge' multiple objects as one json object while reading data from csv file

I want to convert some csv file into json file in nodejs.
While, some of property in the json will be array. Right now I can read a csv file row by row like this:
{"price":1,"bedrooms":"Bedrooms (All Levels): 4"},
{"price":null,"bedrooms":"Bedrooms (Above Grade): 4"},
{"price":null,"bedrooms":"Master Bedroom: 21x15"},
{"price":null,"bedrooms":"Master Bedroom Bath: Full"},
{"price":null,"bedrooms":"2nd Bedroom: 14x13"},
{"price":null,"bedrooms":"3rd Bedroom: 15x14"},
{"price":null,"bedrooms":"4th Bedroom: 15x12"}
BUT I want to get something like this:
`{"price":1,"bedrooms":["Bedrooms (All Levels): 4","Bedrooms (Above
Grade): 4","Master Bedroom: 21x15","Master Bedroom Bath: Full","2nd
Bedroom: 14x13","3rd Bedroom: 15x14","4th Bedroom: 15x12"]}`
Can someone point out some ways? I tried things like fast-csv,csv-parse,ect. But couldn't merge(push or append) the values of the same field into one field as an array.
Thanks.
the code I finished right now:
var fs = require('fs');
var csv = require('fast-csv');
var stream = fs.createReadStream("../../HouseDataDev01.csv");
csv
.fromStream(stream, {columns:true, ignoreEmpty:true, headers :
["price","bedrooms"]})
.on("data", function(data){
// console.log(data);
})
.on("end", function(){
console.log("done");
});
==========
I came up with an idea that maybe I can create an object
var NewHouse = require('../models/NewHouse.js');
//NewHouse is a schema I created before to store the csv data
var test = new NewHouse;
So that I can use the test object something like this:
.on("data", function(data){
for(i in test){
test.i.push(data[index];
}
But I found there are many other properties in test like:$__reset, $__dirty, $__setSchema
How could I write this loop?
Ok, let me explain this...
The main point in my solution is to create some thing like headtag and fieldname{}to record the stream from fs which read csv row by row. I use the headtag to validate the round of the streaming rows. For example for the first round, I need the row's value to be the key of every object in my final json file. If I set a header in fromStream() method, each round's result will conatin the header, I dont know how to 'merge' them, so I chose this 'tricky' way.
Then, as in my final json file, some of(not all of) field will be array. So when I read a second value which is not an empty string "", I should convert the field into an array.usingreadResult[fieldnames[i]]=new Array( readResult[fieldnames[i]]);.
here is the code:
//create a fime stream
var stream = fs.createReadStream(csvfilepath);
//as the file will be read row by row, headtag is pointer to row.
//e.g: headtag = 5, means the stream is reading the 5th row of the csv file
var headtag=0;
//the final stream read result, will be the same format in schema.
var readResult={};
//fieldname records the headers key name.
var fieldnames={};
csv.fromStream(stream,{ignoreEmpty:true})
.on("data", function(data){
if(headtag === 0){
//I assume the first row is the headers,so should make sure the headers' names are the same in your schema
fieldnames = data;
for(var i=+0; i<data.length; i++){
readResult["data[i]"] = {};
}
}
if(headtag === 1){
//some of fields may only conatins one value, so save them as a String
for(var i=+0; i<data.length; i++){
readResult[fieldnames[i]] = data[i];
}
}
if(headtag === 2){
for(var i=+0 ; i<data.length; i++){
//for those field that may contains multiple values, convert them as an array, then push all values in it.
if(data[i]!==""){
readResult[fieldnames[i]]=new Array( readResult[fieldnames[i]]);
readResult[fieldnames[i]].push(data[i]);
}
}
}
if(headtag > 2){
for(var i=+0 ; i<data.length; i++){
if(data[i]!==""){
readResult[fieldnames[i]].push(data[i]);
}
}
}
headtag=headtag+1;
})
.on("end",function(){
readResult.images = images;
//create a time tag
var startdate = moment().format('MM/DD/YYYY');
var starttime = moment().format('H:mm:ss');
readResult.save_date=startdate;
readResult.save_time=starttime;
//save the data in mongodb
NewHouse.create(readResult, function(error, house){
if(error){
console.log(error);
}
else{
console.log("successfully create a document in your mongodb collection!");
}
});
});
On the basis of this question, I updated my code. Now you can read both csv file and images together and save them to mongodb.
for more information check here:
https://github.com/LarryZhao0616/csv_to_json_converter

HTML Use Current page end of URL in target url

long time reader, first time submitter
It looks like i have the ability to insert javascript or HTML in this custom code box, but If it can be done using hTML that would be preferred.
I am trying to get the last string 'Variablex1x' which is dynamic based on the page being viewed. It is a unique identifier that corresponds to records on a different site. I would like to 'grab' that identifier and post it on the end of the target URL. When the user clicks the 'targetdomain.com' url, they are taken to the page of the targetdomain.com/Variablex1x
https://currentdomain.com/portal/x/mycase/Variablex1x
https://Targetdomain.com/Variablex1x
You can try something like this:
$( "#target" ).click(function() {
var Variablex1x;
var newUrl;
Variablex1x = getQueryVariable(nameofvariable)
if(Variablex1x != false){
window.location.href = newurl + "/" + Variablex1x; + "/" + Variablex1x;
}
else{
window.location.href = newurl;
}
});
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
getQueryVariable comes from
https://css-tricks.com/snippets/javascript/get-url-variables/ and will work as long as you know what variable you're looking for.
The idea is when you click on the link instead of actually navigating you'll fire the click function, so you'll need to update the target id. The click function will figure out if you have parameters or not, if you do it will append them to the URL and navigate, if not it will just navigate.
This is not a perfect solution but it should get you started.
IF you don't know what parameters you're looking for here is an answer of how to get those parameters: How can I get query string values in JavaScript?

Select specific data in JSON output

I've created a function that does a http request and then saves some data from the JSON output.
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
// $scope.movieListID = data.results;
$scope.movieListID = data;
console.log($scope.movieListID);
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path
}).then(init);
} else {
console.error('Error happened while getting the movie list.')
}
})
};
This function saves the title, release date en posterpath and that works fine. The problem is that it only saves one release_date while the JSON output has a lot more, but I don't know how to acces that.
This is a example of the JSON output I request
It has a release_date, which I save now, but it also has more information,
releases":{
"countries":[
{"certification":"","iso_3166_1":"GB","primary":true,"release_date":"2015-10-26"},
{"certification":"","iso_3166_1":"US","primary":false,"release_date":"2015-11-06"},
{"certification":"","iso_3166_1":"NL","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"BR","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"SE","primary":false,"release_date":"2015-11-04"},
{"certification":"","iso_3166_1":"IE","primary":false,"release_date":"2015-10-26"},
How would I go about saving the release date for the NL release?
You just need to iterate through the countries array, and check if the country code matches the one you wish to retrieve. For your example with 'NL':
var releaseNL;
for (var i = 0; i < $scope.movieList.releases.countries.length; i++) {
var release = $scope.movieList.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
This is just one of many ways to do this (e.g. you could use angular.forEach, wrap it inside a function, etc.), but this should give you an idea.
Remark: I noticed you have been asking a lot of very basic questions today, which you could easily answer yourself with a bit more research. E.g. this question is not even AngularJS related, but just a simple JavaScript task. So maybe try to show a bit more initiative next time! ;)

How to iterate through $.JSON results array with $.each

I am only getting back the first result in the array, and want to retrieve all the available results.
function runForm(){
$("#stock_news").html("");
var stockSymbol = $("input").val();
//very long str
var newsStocks = "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Ffinance.yahoo.com
%2Fq%3Fs%3D"+stockSymbol+"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22yfi_headlines
%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa'&format=json&diagnostics=true&callback=";
//getJSON
$.getJSON(newsStocks, function(data) {
var headlines = data.query.results.a[0];
//newsStr
newsStr = "<h3 style='text-decoration:underline'>Current Headlines</h3><p><ol>
<li><a href='"+headlines.href+"'>"+headlines.content+
"</a></li></ol></p>";
$("#stock_news").html(newsStr);
});
You haven't given enough information, but I could guess that this var headlines = data.query.results.a[0]; is your issue. It would seem like the other results are there, but you're filtering them out. console.log(data) and console.log(data.query.results) and look at what all is in there. Otherwise, update your question with more information.
Update:
This is a very basic ajax call (with jQuery) and a for loop to loop through and use each result.
$.get('path/here', function(data) {
//if your data is an array
for (var i=0; i<data.length; ++i) {
var item = data[i];
console.log(item);
}
});
Here's a live demo (click), but I'm not going to use the ajax data since the path is not valid.
Here's the same example, but using $.each. I prefer the for loop...why use jQuery for something so simple?
$.get('path/here', function(data) {
$.each(data, function(item, index) {
console.log(index);
});
});

How to use a For loop to create Google Forms checkbox choices

I have tried numerous iterations of the code below, with limited success. The logger seems to show the commands correctly, but the form doesn't seem to EXECUTE the commands. After executing, the form just generates a single non defined checkbox.
Given that I have to repeat this checkbox question multiple times with slightly different question phrasing, I'm trying to reduce my code footprint, and hopefully become more efficient.
Here is the snippet of code I have that's failing:
var storerangestart = 9901;
var storerangeend = 9999;
page402_cbitem1.setTitle('What stores do you have allocated for this project?');
var page402array = 'page402_cbitem1.setChoices([\n';
for (var i = storerangestart; i < storerangeend; i++) {
var storerangecurrent = i + "";
page402array += 'page402_cbitem1.createChoice(' + storerangecurrent + '),\n';
}
page402array += 'page402_cbitem1.createChoice(' + storerangeend + ')\n]);';
Logger.log(page402array);
page402array();
The Logger isn't showing you commands, it's showing you a string. Your code has created a string that contains text that looks like code, but there is no way to execute the content of that string directly in Google Apps Script.
You've got a good idea - you're just stuck trying to manhandle the wrong object types.
Look at the definition of CheckboxItem.setChoices(), you'll see it takes an array of choices as a parameter. The example code may have thrown you because it created the item elements inside the .setChoices() method call:
item.setChoices([
item.createChoice('Cats'),
item.createChoice('Dogs')
]);
You could realize the same result this way:
var choices = []; // create a new array of choices
choices.push( item.createChoice('Cats') ); // Add 'Cats'
choices.push( item.createChoice('Dogs') ); // Add 'Dogs'
item.setChoices( choices ); // set the array of choices
That sets up the opportunity for the loop that you're thinking about. Instead of building a string that contains code, you need to call the various object methods to first build up an array of choices, and then to assign that array as the choices for your form item:
var storerangestart = 9901;
var storerangeend = 9999;
page402_cbitem1.setTitle('What stores do you have allocated for this project?');
var page402array = [];
for (var i = storerangestart; i < storerangeend; i++) {
var storerangecurrent = i + "";
page402array.push( page402_cbitem1.createChoice( storerangecurrent ) );
}
Logger.log( page402array );
page402_cbitem1.setChoices( page402array );