Send text from HTML search bar to backend through JS - javascript

I am using Bootstrap in HTML to create a search page, where users will type a SQL query, and then that SQL query will connect to a backend which will run the query in a database. The backend is in a separate code, and so I'm trying to take the query text and send it to the backend. I am pretty lost on this, and just need an idea of what type of function to build to do this.
The plan is to have an onclick=function and then use the function to send the text to the backend. I can't seem to find any packages or functions that do this, even though I'm sure they are out there/readily accessible. I have looked at AJAX, but can't really find anything that does exactly this.

You don't need any libraries for that
// get the search bar
const input = document.querySelector('input')
// get the button
const button = document.querySelector('button')
// set event listener
button.addEventListener('click', () => {
// run ajax request
fetch('http://yoururlhere?query=' + input.value)
})
<input>
<button>Search</button>

Related

Apollo js refetchQueries does not fire requests

I am using Apollo Client without React, just plain ol JS. I have a classic table and modal that adds things to the backend. Once I add the thing using client.mutate() I'd like to update the table. If the table is not on the last page, it doesn't really matter, the user will eventually click there to get to the new row. But if the user is on the last page or has visited the last page at any point, going back to that page will not display the new row.
In React I was able to do something like
useMyMutation({
variables: {},
refetchQueries: [getOperationName(SomeDocument)]
})
And what this did was refetch the provided query name with its last used variables. I'd like to do something similar and I've been reading the docs and trying this and that but can't even get a query to trigger on the network.
client.mutate(
mutation: MyMutation,
variables: {a:1},
refetchQueries: (e: any) => "all", // nothing I put here ever does anything
)

How to retrieve other users from a Firebase app?

I'm learning JavaScript and I'm trying to built a social app in a specific domain. Nothing big as usual social network because it's for a small community.
So I'm using Firebase, JavaScript ES6 and only one HTML file with an <app>. I already have and auth system, profile page for the current user. But my problem is that I don't know, understand the way to have pages from other's profile.
So as far as I succeed to go it's to get the other's users information from by Firebase database. But I'm stuck in my mind. Should I create an HTML file for each user? I don't think so?
This project is for a certification.
And my other problem is and can't make a verification from data. Well I succeed to check if data exist but it doesn't block the process so it updates anyway and get 2 users with the same name (see code below).
firebase
Atom
savePrenom(event){
let database = firebase.database();
event.preventDefault();
let uid = firebase.auth().currentUser.uid;
database.ref('users').once('value', (snapshot)=>{
snapshot.forEach( el=>{
if(prenom.value === el.val().prenom){
console.log('existe déjà');
}
if (prenom.value != el.val().prenom){
savePrenom.style.display= 'none';
editPrenom.style.display= 'block';
prenom.disabled = true;
database.ref('users/'+uid).update({
prenom: prenom.value
})
}
})
});
}
To solve your first problem: Do not create a html file for each user, that's terrible!
You should rather fetch the data and then use DOM manipulation to insert your data into the page. I do not know which database you are using so I can not give you a code sample for the fetching but only one for DOM manipulations.
Let's say you have the following html:
<p id='description'></p>
You can get the element by id and change it's properties, this is known as DOM manipulation.
document.getElementById('description').textValue = 'Very important'
This assigns Very important to the paragraph (the text will appear when executed by a browser).
Since you said you use plain ES6 only, I'm not going into backend technologies like NodeJS.
I can not help you with the second one since I lack information, please submit some code and tell us more about the technologies you are using.
Ok guys sorry for not responding for all question/answers but i got both solutions.
On the first one. As i could get the informations from a user a simply add some data-classes to passe the data that i could get from firebase. But their was a easier solution. From the moment i can get any information inside a user, i could get the key of each user using snapshot.key (which i forgot). So then it's easy, using a forEach element, each link to each profil use the right information on an other page.
Second question to check if a username already existe when changed for exemple. Well, i started to make a once reference value on my database users. Then if my pseudo.value === el.val().pseudo that means it existe to error message. If not, the user can change his username if wanted with .update for firebase.
database.ref('users').once('value', (snapshot)=>{
let find = false;
snapshot.forEach(el =>{
if(pseudo.value === el.val().pseudo){
//console.log('YEAH');
find = true
}
})
if (find === false) {
savePseudo.style.display= 'none';
editPseudo.style.display= 'block';
pseudo.disabled = true;
database.ref('users/'+uid).update({
pseudo: pseudo.value
})
}
Thanks all.

How do I pass a value from an HTML form submission to a Google Sheet and back to HTML in a Google Apps Script Web App

I'm trying to create a basic time clock web app.
So far, I'm using this script to create this web app which takes the input values and puts them in this spreadsheet for the time stamping part.
I need it to use one of the values from the form and perform a lookup in this sheet (take the longId and find me the name) and return the (name) value to the html page as a verification for the end user that they were identified correctly. Unfortunately, I don't know enough to grasp what I'm doing wrong. Let me know if I need to provide more info.
Edit 1
I'm thinking that I wasn't clear enough. I don't need the user info from entry, I need the user from a lookup. The user will be entering their ID anonymously, I need to match the ID to their info, and bring the info back for them to verify.
Edit 2
Using the link provided by Br. Sayan, I've created this script using this spreadsheet as above to test one piece of this. The web app here spits out: undefined. It should spit out "Student 3" Still not sure what I'm doing wrong.
One way for the next button to grab the student input field:
<input type="submit" onclick="studentName(document.getElementById('student').value)" value="Next..."/>
That sends the value to this func in Javascript.html:
function studentName(value) {
google.script.run
.withSuccessHandler(findSuccess)
.findStudent(value);
}
Which sends it to a findStudent(value) in Code.gs
You do the lookup and the return value goes back to findSuccess( result ) back in Javascript.html. Handle the result from there.
Also consider keeping the stock preventDefault() code that comes with the Web App template in the Help > Welcome Screen.
Please try this one:
(source: technokarak.com)
Also please have a look at:
Retrieve rows from spreadsheet data using GAS
EDIT:
Please make these changes in your function and let us know.
function findValue() {
var data = SpreadsheetApp.openById("15DRZRQ2Hcd7MNnAsu_lnZ6n4kiHeXW_OMPP3squbTLE").getSheetByName("Volatile Data").getDataRange().getValues();
for(i in data) {
if(data[i][3] == 100000003) {
Logger.log("yes");
Logger.log(data[i][0]);
var student = [];
student.push(data[i][0]);
return student;
}
}
}
It is a complicated answer, I have had a lot of success with:
function process(object){
var user = Session.getActiveUser().getEmail();
var key = object.Key;
send(key);
}
function send(k){
var ss =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastR = ss.GetLastRow();
ss.GetRange(lastR,1).SetValue(k);
}
On your html button you will need to have inside the tags
onClick="google.script.run
.withSuccessHandler(Success)
.process(this.parentNode);"
In order for this to work, obviously you will need to have your fields named accordingly.
Edit: The only thing I did not include in the code was a Success handler, which will be in your html of the GAS script. This should point you in a direction that can resolve that.
Hope this helps.

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

In Google Script, how do I embed a script into a button?

The reason I am specifying Google Script and not just javascript in general is because the examples I have found for javascript all use html, which Google Script does not appear to play well with outside of basic formatting commands.
I have one function formSubmitReply() which sends an email based on a form submission, and another addToCalendar() that automatically populates the form submission into a Calendar event. Both of these have been tested independently and function well.
What I am attempting to do is to include an "Add to Calendar" button in the email that will execute addToCalendar() when clicked.
The difficulty I keep encountering is the error "TypeError: Cannot find function addToCalendar in object Generic." How do I get around this?
Here are the relevant pieces of my code:
// Button setup
function doGet()
{
var app = UiApp.createApplication();
// Create button and give it a click handler
var button = app.createButton("Add to Calendar").setId("button");
button.addClickHandler(app.createServerHandler("formSubmitReply"));
app.add(button);
return app;
}
// Email function
function formSubmitReply(e)
{
// Call "button" application
var app = UiApp.getActiveApplication();
/* Additional function code; excluded here */
// Send email
GmailApp.sendEmail(userEmail,
"Event Support Request Submitted",
message +
app.getElementById("button").addToCalendar(e),
{name:"Media Services"});
}
I don't think it is posible to call an apps script function like that from an email button(or any js though i might be mistaken on that one). What you could do is serialize the information from e.Then embed a url to a apps script that will handle the encoded information passed as parameters. Url lengths are limited so you might want to embed a form that submits the data to a apps script if the data you are sending is very large.

Categories

Resources