Compare Field Input with Firebase Entry - javascript

I have an HTML input field where the user needs to type in a specific 6-digit password (handed to the user at an exhibition). Attached to the password on Firebase is an ID psrID (see attached img below).
The ID <?= $page->psrID() ?> is also being used to generate different pages, fetch textures for objects from my CMS etc.
There is only 1 correct password per <?= $page->psrID() ?> available. I can console.log(seeds) to show me the whole array.
If equal = It should display a success message;
If not equal = It should display sth like «wrong password»
Here's how I get the data from Firebase:
var database = firebase.database();
var ref = database.ref();
ref.on('value', gotData, errData);
function gotData(data) {
var seeds = data.val();
console.log(seeds);
}
function errData(err) {
console.log('Error!');
}
And here is the HTML input form:
<form class='seedForm' method='post'>
<label for='seedPassword'></label>
<input id='seedPasswordInput' type='text' name='seedPWD' maxlength='6' class='button' onfocus="this.value=''" value='Enter Pasword' style='text-transform:uppercase' />
<input type='submit' name='button' class='button' value='Register' />
</form>
What function do I have to write to compare the password entered by the user to the password of the ID on Firebase? Thanks for your help!

If I understand you correctly, you want to only read child nodes where a specific property matches a certain value. In that case, you'll want to use a query:
var ref = database.ref();
var query = ref.orderByChild("password").equalTo("HYP4WJ");
query.on('value', gotData, errData);

Related

Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database
The table code is this
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
Then this is taken into the nodeJS server with this command
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
Then at the end it is going to be taken to the RestAPI with that is using this route
#app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I've been trying to find out how to do this for sometime with no luck.
UDATE: I later changed the two items as suggested. The route is
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
and the form is now
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
I get the error that
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
and also this error on the restAPI window
TypeError: 'NoneType' object is not subscriptable
First, you'll need to update your form and inputs to accept user input properly by using the value attribute on the <input> so instead of
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
Do this
<input type="text" value="firstname">
<input type="text" value="lastname">
this will send the values firstname and lastname to your API.
If you need to dynamically accept user input you'll need to watch input changes using javascript and handle the form submit with it too. Check
input value attribute and Javascript form.
To send the data from your node server to your python server you'll need to update
axios.post('http://127.0.0.1:5000/api/adduser')
To
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
Because that way you're passing the form data inside req.body to your python server

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

pug/firebase: add users from input to firebase

I'm trying to add some users from a form to my firebase database. For that I've already linked up firebase config into my main.pug.
But nothing works, I've looked up everywhere and I'm pretty lost.
Need your help and sorry if the code is ugly.
There is my Addform.pug:
div
h2 Add Form
form#addForm
div
label(for='username') Username
input(type='text' name='username' placeholder='Username')#username
div
label(for='name') Name
input(type='text' name='name' placeholder='Name')#name
div
label(for='description') Description
textarea(type='text' name='description' placeholder='Description')#description
div
label(for='email') Email
input(type='email' name='email' placeholder='Email')#email
div
label(for='password') Password
input(type='password' name='password' placeholder='Password')#password
div
input(type='submit' value="ADD" onclick='writeUserData')
div
a(href='../src/editForm.html') Modify
And there my sxript:
// Variables
let username = document.querySelector('#username').value;
let name = document.querySelector('#name').value;
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
let description = document.querySelector('#description').value;
let users = document.querySelector('#users').value;
const submit = document.querySelector('#submit');
// Get a reference to the database service
const userRef = firebase.database().ref().child('Users');
// Add users
const writeUserData = () => {
userRef.push({
username,
name,
description,
email,
password
});
console.log(username, name, description, email, password);
}
// Display users
userRef.on('value', function (snap) {
console.log(snap.val());
users.innerText = JSON.stringify(snap.val(), null, 2);
});
// Delete user
function deleteUser() {
userRef.key('Users').remove();
}
It seems that I can't get the value, it's throwing me one error:
Uncaught TypeError: Cannot read property 'value' of null
Also I can neither see the hard coded data from firebase nor can delete my users.
The problem is your JavaScript selection code. document.querySelector("#xyz") is looking for the element with ID xyz. You have named inputs but would need to give your input elements corresponding IDs as well. An example would be
input#email(type='email', name='email', placeholder='Email')#email
Notice you also need to add a comma before the name attribute

Display Firebase data previously/currently submitted

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

Using form element as variable in Firebase .child()

I would like to use the value of an input from a form element to add a child reference to my firebase data. But, the firebase .child() requires a string, and I've tried to insert a variable (whose value is a string) but it won't work. How do I by pass this?
For example here is a very simple code of an input and submit button. On submission, I want to take the username and add a child reference to my database (under /users ref) in this structure:
{username:{userid: "someID"}}
<html>
<body>
<form>
<input id="testusername" type="text">
<button type="submit" id="testsubmit" value="submit"></button>
</form>
<p>test file for .child()/p>
<script type="text/javascript">
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername');
var username = elusername.value;
alert('username is' + username)
var url = "https://thriftit.firebaseio.com/users";
var firebaseRef = new Firebase(url);
firebaseRef.child(username).push({
userid: "someID"});
});
</script>
</body>
</html>
There's a couple of things.
You're submitting the form before the javascript can run, you need to prevent the page from submitting the page on the click, so remove the type="submit"
I wouldn't do a child on the username, reason being if another user with the same username adds some data, then it would be added under the same username so you'll get two lots of data under the same username.
You want to so something similar to this:
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername'),
username = elusername.value,
url = "https://thriftit.firebaseio.com/users",
firebaseRef = new Firebase(url);
userRef = firebaseRef.push({
username: username,
userid: "someID"
});
console.log(userRef.name()); // this is the uid for the newly generated user
});

Categories

Resources