I'm really a beginner with javascript, but I've been trying to solve the issue below and can't figure it out. Hope anyone can enlighten me.
I try to parse an userID from one website to another by embedding the ID in a url param (/?UID=213), then reading it out and storing it in a javascript variable on the destination website.
//store any userID parsed from the webshop
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userID = urlParams.get('UID');
console.log("userID: " + userID);
Initially this works fine. However, when I browse between pages on the destination website the UID keeps being emptied. Does anyone know what I'm doing wrong?
Related
Trying to render a new page using ejs.
I don't have a big experience with js. Managed good progress so far but at this point I'm stuck.
Currently building a blog, and so far can render the about, or contact pages easily.
When a new user adds a new post, I'm trying to render a new page for that post at localhost:3000/post/test (test is the name of the post).
I receive : Cannot GET /post/title.
If with the same code I only try to check the equality between const storedTitle and const requestedTitle, and if true, console.log("match found") that works just fine.
When using the code below, it doesin't work anymore.
Below is the code I've written for that, but probably in order for one to help me out here, he/she would need to see more than that.
This is my first post on here, sorry if in any case, it does not comply with the community policy.
Thanks for the help!
app.get("/posts/:nameOfPost", function(req, res) {
const requestedTitle = _.lowerCase(req.params.nameOfPost);
posts.forEach(function(post) {
const storedTitle = _.lowerCase(post.titleInput);
if (storedTitle === requestedTitle) {
res.render("post", {
title:post.title ,
content:post.content
});
};
});
I'm currently working on two web apps, one a weather app, and the other a simple login page. I will post explanations for each, as well as the code snippets below the explanations. Thanks to anyone who is willing or able to help.
Edit: The weather app has been updated based on the feedback and now works!
For the weather application, I am using an API to gather weather data, and part of that data is the location. In my JS file, I am trying to obtain the city location from the input field and concatenate it to the API. I've read numerous answers on this site and elsewhere to figure out what I am doing wrong, but nothing seems to work. When comparing my code to others it appears that everything should be working and the inputValue should pass the city location; instead, the inputValue always returns empty. Any reason why this would be happening?
$(document).ready(function() {
//var button = document.querySelector('#submitButton');
var inputValue = document.querySelector('#inputValue').value;
var apiID = config.API_ID;
var apiURL = "https://api.openweathermap.org/data/2.5/weather?q=" + inputValue + "&units=imperial&appid=" + apiID;
$('#submitButton').click(function(){
$.getJSON(apiURL, function(data) {
console.log(data);
document.getElementById('weather').innerHTML = data['weather'][0]['description'];
//document.getElementById('geo').innerHTML = "latitude: " + data.current_observation.display_location.latitude + " longitude: " + data.current_observation.display_location.longitude;
document.getElementById('temp').innerHTML = data.main.temp;
document.getElementById('city').innerHTML = data.name;
document.getElementById('country').innerHTML = data.sys.country;
document.getElementById('icon').src= data.weather.icon;
});
});
});
For the login app, what I am trying to do here is connect it to a calendar API so that the background color/image changes depending on the holiday (currently have it set for a day of the week to test). I keep getting two primary problems. First: I have consistently received a CORS response, but after speaking with the developer of the API, they have informed me that they do not use CORS and the issue I'm facing is likely to do with my choice in browser. That is something I can [hopefully] figure out on my own. Second: the API is consistently returning an undefined Key, despite having the Key stashed in a Config file. I have used Config files on other projects and they tend to work, so I'm uncertain as to why it is failing to properly return the key here. I have checked for syntax and indentation issues, but that doesn't appear to be the problem. I have even tested by placing the API key directly inside of the JS file, but when I run the application it still returns empty (despite working when I place the API+Key directly in the browser). Does anyone know why this would be happening, and how to fix it?
$(document).ready(function(){
var api_Key = config.API_KEY;
var apiURL = "https://holidayapi.com/v1/holidays?pretty&country=US&year=2020&key=" + api_Key;
$("#register-form").hide();
$.getJSON(apiURL, function(data) {
console.log(data);
if(data.holidays.weekday.date.name = "Saturday"){
document.body.style.backgroundColor = rgb(20, 65, 37);
}
});
});
I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start
So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});
I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
#FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {
alert('Firebase')
var newPostKey = null;
// Get a key for a new Post.
newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
alert(newPostKey);
var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');
console.log("Result"+ newPostKey);
var admissionId="KAS"+pad(newPostKey,5);
console.log("Padded number"+ pad(newPostKey,5));
alert(admissionId);
// A post entry.
var postInmateData = {
Inmate_ID: admissionId,
Inmate_Name: $scope.IMfirstnameText,
Inmate_Perm_Address1: $scope.IMAddress1 ,
Inmate_Perm_Address2: $scope.IMAddress2 ,
Inmate_Perm_City: $scope.IMCity,
Inmate_Perm_State: $scope.IMState,
Inmate_Perm_Pincode: $scope.IMPincode,
Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
Inmate_Temp_Address1: $scope.IMLocAddress1,
Inmate_Temp_Address2: $scope.IMLocalAddress2,
Inmate_Temp_City:$scope.IMGcity,
Inmate_Temp_State: $scope.IMGstate,
Inmate_Temp_Pincode: $scope.IMGpincode,
Inmate_Mobile: $scope.IMMobile,
Inmate_DOB: dateofbirth,
Inmate_EmpOrStudent: $scope.IMEmpStudent,
Inmate_DOJ: dateofjoin,
Inmate_ID_Type: $scope.IMIdcardType,
Inmate_ID_No: $scope.IMIdcardno,
Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
Inmate_Status:$scope.IMStatus
};
// Write the new post's data simultaneously in the list.
var updates = {};
updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;
return firebase.database().ref().update(updates).then(function() {
//$scope.ClearInMateDetails();
alert(admissionId);
$scope.statusMessage = "Welcome to Kasthuri Hostel. Your Admission ID is" + admissionId +" . Enjoy your Stay.";
//sendSMS('9488627377',$scope.statusMessage);
alert('Inmate data stored in cloud!');
$scope.ClearInMateDetails();
}, function(error) {
alert (error);
});
}
Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :
My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.