I'm creating a multiuser app and wanted to use keys to product user information. I created a function that updates the child of a database with a generated key. The following function behaves correctly:
unlist(list) {
var postData = {
state: "unlisted",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + list.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
I have a separate function that works similarly to this:
changestate(item) {
var postData = {
state: "listed",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + item.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
In order to make this work correctly, the key that is created from unlist(list) needs to correspond to var newPostKey in changestate(item) and vice versa. How can I make this work?
cfoster5. What I have understood from your question is that the newPostkey from the unlist function should be passed to the changeState(item) function if that's what you want means you can do that by calling promise in the
firebase.database().ref().update(updates).then(function(){
// You can call changestate function and pass the function like below
_changestate(item,newPostkey);
});
and in your changestate function,
changestate=function(item,passedkey){
var newPostKey = passedkey;
}
See my jsfiddle sample
Related
I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.
Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}
if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose
Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();
I'm using Node.js to access this hdPrivateKey but it look like
<hdPrivateKey...>
Not look like normal JS object.
And console.log(address) looks like
<Address: 19o9ghmkUrNVf4d57tQJuUBb2gT8sbzKyq, type: pubkeyhash, network: livenet>
console.log(Object.keys(address)) look like
[ 'hashBuffer', 'network', 'type' ]
Why the key inside address are different?
var bitcore = require('bitcore');
var HDPrivateKey = bitcore.HDPrivateKey;
var hdPrivateKey = new HDPrivateKey();
console.log(hdPrivateKey)
var retrieved = new HDPrivateKey(hdPrivateKey);
var derived = hdPrivateKey.derive("m/0");
var derivedByNumber = hdPrivateKey.derive(1).derive(2, true);
var derivedByArgument = hdPrivateKey.derive("m/1/2");
var address = derived.privateKey.toAddress();
console.log(Object.keys(address))
console.log(address)
// obtain HDPublicKey
var hdPublicKey = hdPrivateKey.hdPublicKey;
The behavior you're seeing is because the object has its own inspect property which is a function and returns a string. When console.log sees that it's logging an object, it looks for that function and uses it if available. So on Node, this logs <foo>:
const o = {
inspect() {
return "<foo>";
}
};
console.log(o);
That's all that the HDPrivateKey object is doing.
If you want to properly inspect the object, use a debugger. Alternately, use utils.inspect with customInspect set to false.
In Node.js, a console.log call the function inspect of the object. In the bitcore-lib there is this method :
HDPrivateKey.prototype.inspect = function() {
return '<HDPrivateKey: ' + this.xprivkey + '>';
};
And this method:
Address.prototype.inspect = function() {
return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
};
i wanted to access an API which responses with some JSON. Therefore I want to configure an 'options' object, which stores all the data which are needed to access the api (url, tokens, id, etc.).
The following version works:
var Options = function (token, id) {
this.token = token;
this.id = id;
this.host = 'http://super-cool-api.com/';
this.path = 'api/fetch/id/';
this.url = '' + this.host + this.path + this.id + '?token=' + this.token
};
var options = new Options('abc', 3);
// options.url = "http://super-cool-api.com/api/fetch/id/3?token=abc"
Basically 'options.url' is all I want. But I've tried to declare a more comprehensive form for the 'options' object, like this:
var options = {
token : 'abc',
id : 3,
host : 'http://super-cool-api.com/',
path : 'api/fetch/id/',
url : '' + this.host + this.path + this.id + '?token=' + this.token
};
// options.url = "undefinedundefinedundefined?token=undefined"
Okay, I understood that I have to access the values in options.url somehow else. But how? Is this even common practice?
What about my first solution? Is it recommended to do it this way?
Regards,
Christoph
Unfortunately this in your second example points to the object that contains the code, i.e. NOT options, that is why the variables are undefined. The first solution is fine, as would be:
function makeOptions(token, id) {
var host = 'http://super-cool-api.com/',
path : 'api/fetch/id/';
return {
token: token,
id: id,
host: host,
path: path,
url: '' + host + path + id + '?token=' + token
};
}
Choose what suits you best.
Both ways you show are OK ways of doing this, as for the most accepted / standard way of doing it, I wouldn't really know.
Here is an example of how to get the Second Option you showed to work correctly :
Set the url of options to be a function that builds the URL and returns it.
var options = {
token : 'abc',
id : 3,
host : 'http://super-cool-api.com/',
path : 'api/fetch/id/',
url : function() {
return '' + this.host + this.path + this.id + '?token=' + this.token;
}
};
And then you can retrieve the value using the following : var testUrl = options.url();
Here is an example JSFiddle for both of your examples, plus my example (Option 3)
I have a survey that stores values to local storage. Trying to make a very simple 'admin' page that its sole purpose is to only display the local storage in an semi organized fashion via table etc. I'm not exactly sure how to go about it.
Here is what i have to store it.
$( document ).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
the key stored is firstname.lastname.element,value. if it could simply display basically like the console view ordered by key that would be great. Any point in a direction would be appreciated.
Unless you really can't manipulate your server side code, I highly recommend that you use $.ajax to post your form to the server and then serve back a response. I doubt that local storage was intended for form submission in quite this way. Otherwise, see below.
In order for you to show your localStorage items on the next page, you need to reference your localStorage items on the next page. After you change window.location.href, the previous page's context is no longer valid, thus name and value no longer exist. You should use something similar to this for both pages:
Submit.html
$(document).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage["name"] = name;
localStorage["person"] = person;
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
Confirmation.html
$(document).ready(function() {
var name = localStorage["name"];
var person = localStorage["person"];
var value = localStorage[person + "." + name];
console.log('stored key: ' + name + ' stored value: ' + value);
});
I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.
How would I go about doing this?
This is an old question but it came up first in google search results.
The solution I went with is similar to jAndy's.
window.location.pathname gives me the page's url without the query string.
I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.
window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
var params = [
"foo=bar",
"base=ball"
];
window.location.href =
"http://" +
window.location.host +
window.location.pathname +
'?' + params.join('&');
That code within your change event handler will do the trick.
For instance:
$('#my_dropdown_id').bind('change', function(){
var params = [
"foo=bar",
"base=" + $(this).val()
];
window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
If you go with the top rated answer, you may want to replace
http://
in the code with
window.location.protocol
so that it works for other protocols, like https or file. So
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
Actually, there a built-in function of location that you can use, the name of the function is assign.
For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.
So for your case you just need below example:
const url = new URL(location.href);
url.searchParams.set('key', 'value');
location.assign(url.search);
Update 2022
I create a TypeScript function to apply redirect with params more easier:
const isClient = (): boolean => typeof window !== 'undefined';
type ParamsType = { [key: string]: string | number };
const redirectUrl = (url: string, params?: ParamsType): void => {
if (isClient()) {
try {
const _url = new URL(url);
if (params) {
const keyList = Object.keys(params);
for (let i = 0; i < keyList.length; i += 1) {
const key = keyList[i];
_url.searchParams.set(keyList[i], params[key]?.toString());
}
}
window.location.assign(_url.href);
} catch (e) {
throw new Error('The URL is not valid');
}
}
};
export default redirectUrl;
If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:
var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo¶m2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.
If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.
$("#sortby").change(function () {
var queryString = getQueryStrings();
// Add new params to the querystring dictionary
queryString["sortby"] = $("#sortby").val();
window.location.href =
window.location.protocol + "//" +
window.location.host +
window.location.pathname +
createQueryString(queryString);
});
// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
}
}
return assoc;
}
function createQueryString(queryDict) {
var queryStringBits = [];
for (var key in queryDict) {
if (queryDict.hasOwnProperty(key)) {
queryStringBits.push(key + "=" + queryDict[key]);
}
}
return queryStringBits.length > 0
? "?" + queryStringBits.join("&")
: "";
}
I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.
Using the code
window.location = window.location.pathname
+ window.location.search + '#tabs-4';
did'nt work for me but below code did.
location = "#tabs-4";
location.reload(true);