Implementing search bar functionality with AJAX and HTTP Requests - JavaScript - javascript

I am attempting to create a search function that finds data depending on the query that is entered (so a typical search bar in my HTML). I need it to search the title of the books that I have stored in my database which can be accessed in the GET requests location. So far, I have managed the code to get the array from the database, but I am trying to search by title.
var xhttp = new XMLHttpRequest();
const books_url = "http://127.0.0.1:3000/books"
xhttp.open("GET", books_url, true);
xhttp.addEventListener('load', function() {
function bookSearch() {
var search = document.getElementById('searchBar').value
document.getElementById('booksFound').innerHTML = ""
console.log('Looking for ' + search)
console.log('Search button works')
}
document.getElementById('searchBtn').addEventListener('click', bookSearch, false)
document.getElementById("divShowBooks").innerHTML = this.responseText;
console.log(xhttp);
console.log(this.response);
});
xhttp.send();
Here is my HTML code where I am working with the search bar and attempting to display it.
<section class="bookSearchBar">
<h4>Search Books</h4>
<form method="GET" id="searchBooks" class="form-inline md-form form-sm active-pink-2 mt-2">
<input id="searchBar" class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Search by Title" aria-label="Search">
<button id="searchBtn" type="button">Submit</button>
<i class="fas fa-search" aria-hidden="true"></i>
</form>
<div id="booksFound"></div>
</section>
Please inform me if you need more information.
UPDATE: Re-posted for hopefully a less confusing title.

I'm gonna assume your search works using term as the GET variable (i.e a search looks like this: http://127.0.0.1:3000/books?term=godfather)
const books_url = "http://127.0.0.1:3000/books";
document.getElementById('searchBtn').addEventListener('click', bookSearch, false);
function bookSearch() {
var search = document.getElementById('searchBar').value;
document.getElementById('booksFound').innerHTML = "";
console.log('Looking for ' + search);
console.log('Search button works');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () { // this is what happens when an answer is returned
if(xhttp.readyState === 4 && xhttp.status === 200) { // a valid answer
document.getElementById("divShowBooks").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", books_url, true);
xhttp.send("term=" + search ); // sending the term variable to the search page
}
you should read up on these basic principles, or this is gonna be confusing:
GET parameters
AJAX
hope this gets you there - good luck and happy new year!

Related

How can I display textarea client input on website without changing URL?

I am attempting to implement a feature on my website, where a user can input a comment into a textarea and have it display the comment, below the comment box. For backend I am using bottle. At the moment, bottle is recognizing the input, and when input is submitted, a new url loads displaying only the input of the textarea.
When submitted, I need the textarea input to be displayed below the textarea box, without changing the webpage.
Here is HTML textarea input
<div>
<p>
Add a comment
</p>
<form action="/comment" method="post">
<textarea name="text"></textarea>
<input type="submit" value="Submit">
</form>
</div>
Bottle in main.py
#route('/comment', method = 'POST')
def submit():
com = request.forms.get('text')
print('Printing comment...')
print(com)
return com
index.js, (i'm not sure how to integrate this function)
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("GET", "/comment");
xhttp2.send();
return false
}
Call loadCom() from an event listener.
document.querySelector("form").addEventListener("submit", e => {
e.preventDefault(); // prevent reloading the page
loadCom();
});
loadCom() needs to use the POST method to send the value of the textarea to the controller.
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("POST", "/comment");
xhttp2.send('text=' + encodeURIComponent(document.querySelector('[name="text"]').value);
return false
}

javascript function with variable needed to trigger a url with value from within script

i have an html page with some inputs, i need to trigger a js function that will ultimately lead to triggering a url GET or POST (with out credentials) the problem is i need to see this in my url
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
instead I see this
http://localhost:8080/?keyword=oven&email=
Don't worry about the email; I am using a thymleaf for front end and java for back end database to save email.
For now i really need to trigger the url with the right url which is this
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
my code is as follows (index.html)
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="submit" onclick="equipmentSearchFn()">Search</button>
</form>
</div>
for script i have within my html file (index.html)
<script>
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
document.getElementById("keyword").innerHtml = keyword;
document.getElementById("email").innerHtml = email;
let xmlHttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
}
}
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
//window.location = url + keyword;
xmlHttp.open('GET', url, true);
xmlHttp.send();
}
</script>
i am much obliged...
You have two problems here. The first it the "submit" button. Unless you stop the click event with javascript, the button will POST the values to your Form.
The second problem is the AJAX request, which I think you don't need at all.
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
window.location = url + keyword;
}
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="button" onclick="equipmentSearchFn()">Search</button>
</form>
</div>

Javascript: Trouble taking user input and running it in another function

New to the JS world and I have a few questions. I'm trying to take the user's input and run it through another function but seem to be getting stuck. When I accept the user input using window prompt, the code works correctly.
function lookup(address, callback) {
var electionId;
var address = prompt("Enter your address: ");
var req = gapi.client.request({
'path': '/civicinfo/v2/voterinfo',
'params': {
'electionId': electionId,
'address': address
}
});
req.execute(callback);
}
<h1>Places To Vote</h1>
<p>Find a polling location near you.</p>
<div id="results"></div>
However, I'd like to have the user place their information in an input form and click a submit button. I can't seem to get the user input to go through my other functions once an input form is in place. Help? Please excuse my Frankenstein code.
var userSubmitJS = document.querySelector('userSubmit');
var userInputJS = document.querySelector('userInput');
var address;
userSubmitJS.addEventListener('click', function()) {
address = userInputJS.value;
alert(address);
}
function lookup(address, callback) {
var electionId;
var req = gapi.client.request({
'path': '/civicinfo/v2/voterinfo',
'params': {
'electionId': electionId,
'address': address
}
});
req.execute(callback);
}
<h1>Places To Vote</h1>
<p>Find a polling location near you.</p>
<form>
<input id="userInput" type="text" placeholder="Enter your address">
<button type="submit" id="userSubmit">Submit</button>
</form>
<div id="results"></div>
There were two errors in your code:
if you want to get an element by ID, you need to pass # to querySelector (e.g. #userSubmit and #userInput)
an "Uncaught SyntaxError" in your addEventListener (the position of the closing ) was wrong)
To pass address to the lookup function, you can just call
lookup(address, my_callback)
where my_callback is the name of the callback function.
var userSubmitJS = document.querySelector('#userSubmit');
var userInputJS = document.querySelector('#userInput');
var address;
userSubmitJS.addEventListener('click', function(event) {
event.preventDefault();
address = userInputJS.value;
alert(address);
lookup(address, my_callback);
});
function lookup(address, callback) {
console.log('lookup');
// ...
callback();
}
function my_callback() {
console.log('my_callback');
}
<h1>Places To Vote</h1>
<p>Find a polling location near you.</p>
<form>
<input id="userInput" type="text" placeholder="Enter your address">
<button type="submit" id="userSubmit">Submit</button>
</form>
<div id="results"></div>

How can I fix this html code to not display sensitive information to the user?

I am creating a html form to capture applicants' inputs and then send a POST request to an api with the data. I do not know how to go about hiding three specific values from something like 'View Page Source' or console.log(). I need to store the values securely and still be able to use them in the HTML form.
I know I will probably have to rewrite my solution but I do not know the best way to go about this. Is there a way to store the values of the api keys in a database?
Here are the three values in question:
<body>
<main role="main" class="container-fluid">
<form id="form1" name="form1" onsubmit="beforeSubmit(); return false;">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
<script type="text/javascript">
var merID = "1234567";//need to store these values somewhere else!!!!!!!
var log = "API123";
var pass = "1234567";
//even if these values are moved they would be viewable by something like console.log(obj)
document.getElementById("merchantID").value = merID;
document.getElementById("login").value = log;
document.getElementById("password").value = pass;
</script>
And here is where I make the API call:
<script type="text/javascript">
beforeSubmit = function () {
//======================================================================================================
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//======================================================================================================
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://someurl.com/enroll.svc/JSON/CreateMerchant", true);
xhttp.setRequestHeader("Content-type", "application/json");
var obj = JSON.stringify($('#form1').serializeObject());
console.log(obj);//security concern! all someone would have to do is cntrl+shift+j when the form is submitted
//this log command would display the entire JSON object including the merchant ID, Login and Password
xhttp.send(obj);
} //=====================================================================================================
</script>
I am very new to this. The code does what it is supposed to aside from sensitive information easily being viewed by inspecting the page source. Any suggestions of for a better/more secure way would be appreciated.
Its shouldn't be too hard put your api in a php variable then insert your variable into your database table.
Then use select to take it out when you need it also php is not readable from view source.
If you don't know how to input and select from databases there are plenty of tutorials out there.
Your code is a horrid mix of unnecessary serialisation you are not using and a weird event handling of beforesubmit.
This is how a generic jQuery ajax looks like
$(function() { // page load
$("#form1").on("submit", function(e) {
e.preventDefault(); // cancel the submit
$.post("https://someurl.com/enroll.svc/JSON/CreateMerchant", // url
$(this).serialize(), // serialising the form
function(result) {
console.log(result); // do something with the result of the submission
});
});
});
<form id="form1" name="form1">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
</form>

ajax callServer ajp still empty

I am trying to make a website for a project so it will be locally and I am in the point where I want to use Ajax for a login form I made. I dont know very much about ajax but this is a code I found it doesnt work but I dont know what else I should do, and what exactly am I expecting. An ajp file with what inside? Thanks in advance
This is the javascript code:
function callServer(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlString =
"<profile>" +
"<username>" + escape(username) +"</username>" +
"<password>" + escape(password) +"</password>" +
"</profile>";
// Build the URL to connect to
var url = "file:///C:/Users/admin/Documents/project/savelogin.jsp";
// Open a connection to the server
xmlHttp.open("POST", url, true);
// Tell the server you're sending it XML
xmlHttp.setRequestHeader("Content-Type", "text/xml");
// Set up a function for the server to run when it's done
xmlHttp.onreadystatechange = confirmUpdate;
// Send the request
xmlHttp.send(xmlString);
}
This is the html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="login.js"></script>
<title>Project-Login</title>
</head>
<body>
<form id="loginform">
<div>
<p id="insertinfo">Type your info to log in your account:</p>
<label for="Username">Username:</label>
<input type="text" id="username" placeholder="Type your username"/>
</div>
<div>
<label for="password">Type password:</label>
<input type="text" id="password" placeholder="Type your password"/>
</div>
<div class="loginButton">
<input type="submit" value="Log in" class="loginbutton" onclick="callServer()" />
</div>
</form>
</body>
</html>
What will you be doing with the values that you retrieve from HTML?
Her is an example from w3schools:
http://www.w3schools.com/ajax/ajax_php.asp
But what you want is:
<script>
function retrieveValues() {
var value1 = document.getElementById("username").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "thePhpPage.php?q=" + value1, true);
xmlhttp.send();
}
But here the variables are passed onto a php function. If you want something similar on your local machine you need to install lamp or wamp depending on your OS.

Categories

Resources