I am trying to make a chatroom where the messages are stored in google firebase. I have not learned Javascript yet, but my schoolbook contains all the necessary Javascript code that I need for the task. The chatroom will have two inputs, one for username and one for a message, and a button to send the message. My problem is that whenever I try to send the message it won't store itself in the firebase and thus not be displayed. I apologize for the IDs and classes being in Norwegian, but I'm afraid that if I try to change it I will mess up something in the process.
<form id="skjema">
<input type="text" id="inpAvsender" required placeholder="Brukernavn">
<input type="text" id="inpMening" required placeholder="Melding">
<button type="submit" class="button">Send</button>
</form>
<article id="txtMeldinger"></article>
// google firebase snippet here //
<script>
let database = firebase.database();
let meldinger = database.ref("meldinger");
let skjema = document.
getElementById("skjema");
let inpAvsender = document.
getElementById("inpAvsender");
let inpMening = document.
getElementById("inpMening");
let txtMeldinger = document.
getElementById("txtMeldinger");
function visMelding(snapshot) {
let melding = snapshot.val();
let meldingTekst ='<p>
<b>${melding.avsender}:</b>
<i>${melding.tekst}</i>
</p>';
txtMeldinger.innerHTML = txtMeldinger.
innerHTML + meldingTekst;
}
function regNyMelding(evt) {
evt.preventDefault();
var nyMelding = {
avsender: inpAvsender.value,
tekst: inpMening.value
};
meldinger.push(nyMelding);
inpMening.value ="";
}
meldinger.on("child_added", visMelding);
skjema.onsubmit = regNyMelding;
</script>
Related
I am trying to implement an auto complete feature on a flask app where I want that when the user input characters, a windows will appear with options with stock symbols.
My current /search html is basic intentionally becaue I want to debug as I go along
def search():
from ftplib import FTP
directory = 'symboldirectory'
filenames = ('otherlisted.txt', 'nasdaqlisted.txt')
ftp = FTP('ftp.nasdaqtrader.com')
ftp.login()
ftp.cwd(directory)
for item in filenames:
ftp.retrbinary('RETR {0}'.format(item), open(item, 'wb').write)
ftp.quit()
# Create pandas dataframes from the nasdaqlisted and otherlisted files.
nasdaq_exchange_info = pd.read_csv('nasdaqlisted.txt', '|')
other_exchange_info = pd.read_csv('otherlisted.txt', '|')
nasdaq_exchange_info=nasdaq_exchange_info.query('ETF == ETF')
nasdaq_exchange_info = nasdaq_exchange_info.rename(columns={'Security Name': 'Security_Name'})
nasdaq_exchange_info=nasdaq_exchange_info.query("Security_Name.str.contains(request.args.get('q'), case=False)")
print(nasdaq_exchange_info)
return render_template("search.html", nasdaq_exchange_info=nasdaq_exchange_info)
My issue is in
nasdaq_exchange_info=nasdaq_exchange_info.query("Security_Name.str.contains(request.args.get('q'), case=False)")
print(nasdaq_exchange_info)
I get name 'request' is not defined error (if I'll input Security_Name.str.contains('apple', case=False) for example it will get printed.) Also I tried every variation I could think of but I get syntax error.
My html look like this:
<body>
<input autocomplete="off" autofocus placeholder="Query" type="text">
<ul></ul>
<script>
let input = document.querySelector('input');
input.addEventListener('input', async function() {
let response = await fetch('/search?q=' + input.value);
let nasdaq_exchange_info = await response.json();
let html = '';
for (let symbol in nasdaq_exchange_info) {
let ticker = nasdaq_exchange_info[Security_Name].symbol;
html += '<li>' + ticker + '</li>';
}
document.querySelector('ul').innerHTML = html;
});
</script>
</body>
Is there a knwon way of implementing the user typing in q and serach the db for it? I know how to do it in a db using sql but I am trying to avoid that.
try applying fstrings like that:
nasdaq_exchange_info=nasdaq_exchange_info.query(f"Security_Name.str.contains({request.args.get('q')}, case=False)")
I am pretty new to using localStorage, so excuse my ignorance and the potential repetition of this question. I couldn't get any answer yet.
I have a form with a lot of input tags. I am storing their values in a var called data var data = document.querySelectorAll( "input" ).value;
when I do window.localStorage.setItem('data', JSON.stringify(data.value))
it stores data in the storage with a value of undefined.
I get that my var data isn't really catching all the user input values, but I couldn't figure out how to do it.
My intention is to make var data an object that stores other objects that have the values of the input fields. then push this data to the localStorage. WITH PURE JS
Try this code, it writes to localStorage and reads from it to console (stackoverflow insert code tool doesn't allow to work with localStorage, that is why the code is in different JS sandbox): https://plnkr.co/edit/0e1R1aDTneQ1RA0Dvasj?p=preview
code:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
<script>
let data = document.querySelectorAll("input");
let formData=[];
console.log('data', data);
for(let i=0; i<data.length; i++){
formData.push({ name: data[i].name, value: data[i].value })
}
console.log("formData for localStorage", formData)
localStorage.setItem('formData', JSON.stringify(formData));
let output = localStorage.getItem('formData');
console.log('output', JSON.parse(output));
</script>
</body>
</html>
As noted in the comments, you need to loop over your inputs to get the values and then store them in localStorage. For example:
const inputs = document.querySelectorAll('input');
const data = [];
for (const input of inputs) {
data.push(input.value);
}
window.localStorage.setItem('data', data);
Also, if you are really trying to store the data as JSON (perhaps why you were trying to use JSON.stringify()), then you could do something like the following (although it would be better if your input elements had unique id or name values you could use as keys rather than just the index of the selected input as in the example below).
const inputs = document.querySelectorAll('input');
const data = {};
inputs.forEach((input, i) => {
data[i] = input.value;
});
window.localStorage.setItem('data', JSON.stringify(data));
I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!
So I'm simply trying to make a page where I have an input for a user's name and age, then they submit that, and it sends that to the Firebase database, and that is working perfectly. The other thing I'm trying to do is display the data submitted in a "view" section. So just display the user's name and age below. I'm struggling to understand/get why my code is not working -- I have an h3 in place that should be replaced by the data that is stored in my database.
Here is my code for the retrieval section
'Age' is what one category of children is called (the other is 'Name')
<h2> View</h2>
<h3 id="showData"> Hello</h3>
<script>
showData = document.getElementByID('showData');
var firebaseDataRef = firebase.database().ref().child('Age');
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.value;
});
the rest of my code:
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://addview-c21e6.firebaseio.com'),
currentMessageRef = rootRef.child('Name'),
currentNameRef = rootRef.child('Age');
function addFB()
{
currentMessageRef.push(userName.value);
currentNameRef.push(userAge.value);
userName.value = '';
userAge.value = '';
}
.value is not a property of DataSnapshot. You need to call the .val() method on it.
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.val();
});
docs: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#val
I am doing a school project on creating a web site. I have managed to save user data into local storage upon signing up for an account. I want to retrieve and display the saved user data from local storage into an edit profile page, such that when I load the edit profile page, there would be some data already shown in the page.
For example in social media accounts whenever we want to edit our profile, our current information would be shown, and we just edit our info from that page. How do I achieve this?
Here are my codes:
<script>
var currentUser=null;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
</script>
I know the console.log only shows the data in console, but I need the data to be shown in the text box instead when users go to the edit profile page.
Is the following script correct to display a username in the username text box?It didn't work for me though.
<p>
<label for="newusername">Change Username:</label>
<input type="text" name="username" onload="valueAsPlaceHolder();"
id="username" required="required"/>
<!--<script>
function valueAsPlaceHolder() {
var changeUsernameInput = document.getElementById("username");
localStorage["username"] = changeUsernameInput.value;
var changeUsernameSetting = localStorage["username"];
if (changeUsernameSetting == null) {
changeUsernameInput.value = "";
}
else {
changeUsernameInput.value = changeUsernameSetting;
}
}
</script-->
</p>
You should have to modify the loadUserData function like below. I have set example for username you can follow for all fields like name, email and password.
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
}
}