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

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
}

Related

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>

Implementing search bar functionality with AJAX and HTTP Requests - 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!

JavaScript search in many txt files

I have a search bar in HTML page and I have many text files and I want to do a search with Javascript to find String in all the text file. I want to know if its possible to do it with Javascript. I can do it search in one text but not many. Here is search script and the HTML.
function readTextFile(file,str)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
if(allText.search(str) != -1){
alert("exist");
alert(location.pathname);
}else{
alert("not exist");
}
}
}
}
rawFile.send(null);
}
<div>
<form name="search" onsubmit="return readTextFile('All-html.txt',this.string.value);">
<input name="string" onchange="n = 0;">
<input type="submit" value="Go">
</form>
</div>
Thanks.
Assuming your function works (readTextFile(file,str)), I would write a new function that iterates over the files list and call readTextFile for each file. Also return true/false if the str was found.
function searchAllfiles(str){
var files = ["file1", "file2", "file3"];
files.forEach(function(filename) {
found = readTextFile(filename, str);
if (found){
alert(str + " was found in " + filename);
}
});
}
Edit:
You can't get the files list from the server using only JS.
1 Option is to keep track on the clients side of the files the user adds dynamically
Second option is to pass the list from the server. Maybe you can maintain the files list inside 1 file and get the paths by reading it or build a service that will return the files list and then call this service with an Ajax call via JS.

Read values from multiple textboxes and send them as a single string using JavaScript

I'm trying to read the value from multiple textboxes and then send those values in a single string to my PHP processing page where it will be added to the database table.
Also the above mentioned textboxes are made using JQuery dynamically the filed is hidden from the user it serves as storage compartment for the ID of the selected error using the drop down.
I know how to get this done in PHP but I'm using javaScript in middle to hand over the data from the form to the PHP.
I've posted almost all the code which is directly connected with the dynamic add/remove area those functions are working but added them just in case.
My issue is I can't get the value of the hidden text boxes named "errorId" and put them in a single string to send to the PHP page.
I want to do something like this IE: &errorId=19, 1, 15, 34 .... etc
I did try lot of suggestions from SO but all of them gave me the variable as undefined. As you can see my last attempt is still in my code document.getElementsByName("errorId")[0].value;. I'm trying to do this part in JavaScript hope some one can teach me how to get this done.
HTML:
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span>Error Name</span>
</div>
<div class="error-Column">
<div class="error-container">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<select id="errorName" class="errorName">
<option disabled></option>
</select>
<input class="errorId" size="1" name="errorId" readonly hidden>
<input type="button" class="addRow" value="Add" disabled />
<input type="button" class="delRow" value="Delete" />
</div>
</div>
</div>
</div>
Submit Function:
function timeSheetAdd() {
var jType = document.querySelector("input[name=jType]:checked").value,
errorId = document.getElementsByName("errorId")[0].value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("msgID").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "../Functions/TimeSheetSubmit.php?jType=" + jType + "&errorId=" + errorId, true);
xmlhttp.send();
}
Function I use to populate the drop down:
//The function to drag the error data from the table qcErrors and populate the drop downs
function getError() {
//Get the selected ID using this.is in client side HTML then breaks it up using this to get the ID only
var errorSelect = document.getElementById("errorName");
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (errorSelect.selectedIndex === 0) {
errorSelect.innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open("POST", "../functions/getQcErrors.php?error=geterror", true);
xmlhttp.send();
}
Dynamic button creation and enable / disable functions in jQuery:
//Disable the Start button after single click
function startBtnDisable() {
document.getElementById("getStartTime").disabled = 'true';
}
//Disable the End button after single click
function endBtnDisable() {
document.getElementById("getEndTime").disabled = 'true';
}
//Enable job type radio buttons
function enableJtype() {
var client = document.getElementById("clientSelect").value,
strTimeBtn = document.getElementById("getStartTime"),
jType = document.getElementsByClassName("jType");
if (client !== "") {
if (client === "Break") {
for (var j = 0; j < jType.length; j++) {
jType[j].disabled = true;
}
strTimeBtn.disabled = false
} else {
//For loop to enable radio buttons
for (var i = 0; i < jType.length; i++) {
jType[i].disabled = false;
}
}
} else {
for (var j = 0; j < jType.length; j++) {
jType[j].disabled = true;
}
}
}
// Show or hide the div which contains the error inputs
// If the QC job type is selected.
$(document).ready(function() {
$('.jType').click(function() {
if ($('#qc').is(':checked')) {
$('#jType-container').show(); //Show the content of the error container div
getError(); //Populates the error name drop down
} else {
$('#jType-container').hide();
}
$('#getStartTime').prop('disabled', false); //Enables the get start time button
});
$('#getStartTime').mousedown(function() {
$('#getEndTime').prop('disabled', false); //Enables the get end time button
$('.addRow').prop('disabled', false);
});
$(document).on('change', '.errorName', function() {
var sid = $(this).find('option:selected').attr('id');
$('.errorId').filter(':last').val(sid);
})
});
// Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var selectedIndex = $('.errorId').filter(':last').val();
if (selectedIndex !== "") {
//$('.error-Column .error-container:first').clone().appendTo('.error-Column');//Clones the row
// --- Disabled due to is clones and resets the value of the drop down box
var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
$clone.find('.errorId').val(''); //Find the errorId text box and makes value = ""
$clone.find('select.errorName').focus(); //When cloned set the focus to the error selector
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false); //Add a row and disables add buttons above
resetErrorNo(); //Reset the values
getError(); //Pulls the errors from the DB
} else {
alert("Select an error name");
}
}).on('click', '.delRow', function() {
var $btn = $(this);
if (confirm('Your sure you want to remove this?')) {
$btn.closest('.error-container').remove(); //Removes the row
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false); //Enables the last add button
resetErrorNo(); //Reset the values
}
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
If I understand:
var error_inputs = document.getElementsByName("errorId");
var errorIds = [];
for(var i=0; i<error_inputs.length; i++) {
errorIds.push(error_inputs[i].value);
}
var errorId = errorIds.join(', ');
My issue is I can't get the value of the hidden text boxes named "errorId" and put them in a single string to send to the PHP page
errorId = document.getElementsByName("errorId")[0].value;
In the above line, you are taking only the first errorId's value.
if you want to get all the values, use
var value = [];
var e = document.getElementsByName("errorId");
for (a of e)
value.push(a.value);
value = value.toString();
console.log(value);
<input name="errorId" value="1" />
<input name="errorId" value="2" />
<input name="errorId" value="10" />
<input name="errorId" value="12" />
Edit: you tagged the question with jQuery, but it seems you are using plain javascript. In case you don't use jQuery, refer to #pagetronic's answer.
With this jQuery selector you can get all the elements containing your errorId code (selecting by class):
$('.errorId')
and then you can loop on them, appending the element value to variable that you can use in the POST, something like this:
var toPost = '';
$('.errorId').each(function() {
toPost = toPost + ' ' + $(this).val();
});

Using AJAX to send and receive info from a server

I'm working on a page that is supposed to interact with the server via AJAX, but my experience with AJAX is extremely limited. Here's how the page is supposed to work.
When the button is clicked, if the "test" radio button is clicked, just display a pop up saying the input was valid.
When the button is clicked, if the "live" radio button is clicked, the program is supposed to send a request to the server using the URL "http://cs.sfasu.edu/rball/351/exam2.php" with the contents of the input box being the value for the "name" parameter.
The page will then send back a JSON object that I need to parse into a regular variable.
I'll leave the rest of the JSON stuff alone since that's not what I asked.
So far I have the design of the page done, but like I said I don't really know what I'm doing with the AJAX stuff. I have some code written for it, but not sure that it's right.
Here is my code:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
And here is a link to my page on our server:
cs.sfasu.edu/cs351121/exam2.html
Also, I know it says exam, but this is actually just a review we were given for the actual exam that's next week. I'm just trying to figure out how this works but don't know what I'm doing wrong.
I'm not sure what the problem is. The code is correct
Ok now i get the problem. You are calling the request variable outside the scope. You are declaring the request variable inside your ajaxStuff function so its only accessible in that area. Thats why it is undefined. Try this:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
to get the result just do this
TTrequest.send();
var response=TTrequest.responseText;
I know, I do not see the jQuery tag, but consider it if there are no framework restrictions.
Example:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});

Categories

Resources