Simple HTML form input field with multiple values from barcode scanner - javascript

I know barcode scanner is just another keyboard that sends keycode 13 after every scan, I have a very simple form with just one input field, I want to be able to scan multiple barcodes and click submit to POST data. I think I would would need a javascript for this, but I am no good with javascripts.
The end result would look something like this. You can see multiple barcodes have been scanned and they appear at the bottom of the picture.
The goal is to scan desired number of barcodes without touching the keyboard, when done scanning press the submit button with the click of mouse. When I click submit they should be posted to another page.
I am sure this is a simple thing for someone who is good at javascript.
Here is the HTML form code.
<form action="myform5.php" method="post">
<p>First name: <input type="text" name="serial" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
My question is how I can make it do what I described above?
Thanks in advance.

This should work.
var codes = "";
var codes_el = document.getElementById('codes');
var output_el = document.getElementById('output');
function process_key(event){
var letter = event.key;
if (letter === 'Enter'){
event.preventDefault();
letter = "\n";
event.target.value = "";
}
// match numbers and letters for barcode
if (letter.match(/^[a-z0-9]$/gi)){
codes += letter;
}
codes_el.value = codes;
output_el.innerHTML = codes;
}
<form method="POST" action="myform5.php">
<input onkeydown="process_key(event)" />
<input type="submit" value="Send" />
<input type="hidden" name="codes" id="codes" />
</form>
<pre id="output">
</pre>
Then you can get in myform5.php like so:
<?php
// codes will be a string of barcodes seperated by "\n"
$codes = $_POST['codes'];
// get as array like so
$barcodes = explode("\n", $codes);
// build up string of barcodes
$barcode_str = "";
$prefix = '';
foreach ($barcodes as $barcode){
$barcode_str .= $prefix . "'" . $barcode . "'";
$prefix = ', ';
}
$query = "select * from hdds where serial IN (" . $barcode_str . ");";
/* do things with query here */
// once your done processing
// redirect the user back to the form page
header("Location: FormPage.html");
?>
I assume your barcodes are strings in the DB.
So you have to wrap each of the barcodes in the query.

Related

Want both PHP & JS form (empty fields/password match) validation?

I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.

Form field (default text) + some more text

I have a form field with default text, but my users have to paste a filename after this default text. How can I achieve that?
/td><th width="200px">VideoLink</th><td><input type="text" id="VideoLink" name="VideoLink" value="<?php echo $video_rec['VideoLink']; ?>"></input></td>
$video_rec['VideoLink'] = "rtmp://test123.cloudfront.net/cfx/st/mp4:";
My user has to paste the filename in that form field, but when the form is submitted that field should contain rtmp-url + filename (test.mp4)
Sample = rtmp://test123.cloudfront.net/cfx/st/mp4:TEST.mp4
I did check this solution How to keep some default text in the input field?, but when i right click to paste it removes the default text.
Something like this:
HTML:
<input type="text" id="defaultLink" name="defaultLink" class="defaultLink"
value="rtmp://test123.cloudfront.net/cfx/st/mp4:" disabled />
<input type="text" id="videoLink" name="videoLink" />
<input type="hidden" id="completeLink" name="completeLink" />
<input type="button" onclick="appendLink();" value="Append" />
CSS:
.defaultLink {
min-width: 235px;
border: none;
background-color: transparent;
}
JS:
function appendLink(){
var defaultLink = document.getElementById('defaultLink').value;
var videoLink = document.getElementById('videoLink').value;
var completeLink = defaultLink + videoLink;
alert(completeLink);
document.getElementById('completeLink').value = completeLink;
}
Then, you can get complete URL from completeLink request attribute / parameter.
DEMO
You shouldn't trust your users to provide correct input, let them paste as they wish, you can guide them with a note or label, ex. please include the "rtmp://" bit but ultimately you should validate the input server side.
You can try this:
$string = 'rtmp://test123.cloudfront.net/cfx/st/mp4:TEST.mp4';
//$string = 'test123.cloudfront.net/cfx/st/mp4:TEST.mp4';
// make sure to also strip any leading or trailing whitespace using trim()
// you can also process the input string even further before testing the protocol
if (!stripos($string)){
$url = 'rtmp://' . trim($string);
}
else{
$url = trim($string);
}
print $url;

Javascript two weird problems: POST not working, window.location.href not working

I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >

Sending data to Mysql through a showprompt in Javascript

I would like to send data that the user the filled in a show prompt box. I originally planned to send the data from a regular form, but changed my mind and want to do it through a show prompt box.
Here is my code:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("question");
if (name!=null && name!="")
{
document.write("<p>This is your question " + name + "</p>");
}
}
</script>
the html for the form is:
<form id="propose" name="input" action="insertpropose.php" method="post"><br/>
<input type="submit" onclick="show_prompt()" value="propose" />
</form>
and the PHP is
$query="SELECT propose* FROM propose";
$result=mysql_query($query);
$result = mysql_query("SELECT * FROM propose");
I m new to programming, so I hope I was clear.
You can do something to this effect:
HTML:
<form id="propose" name="input" action="insertpropose.php" method="post"><br/>
<input type="submit" onclick="show_prompt()" value="propose" />
<input type="hidden" name="propose" value="">
</form>
Javascript:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("question");
if (name!=null && name!="")
{
//set the hidden input value to the value entered in the prompt
document.input.purpose.value = name; //document.input referring to the form named 'input'
document.input.submit(); //submit the form
}
}
</script>
Your SQL is a bit wonky, so I changed it to function how I assumed you wanted it to work:
$purpose = $_POST['purpose'];
$query="SELECT propose FROM propose WHERE purpose = ". $purpose;
$result=mysql_query($query);
Note that using SQL in this way is HIGHLY insecure.
This should give you your desired effect, although this probably isn't the best way to go about doing it.

How to color HTML elements based on parsing a user command string

I'm working on a little parsing thing to color objects.
For an example, you could type red:Hi!: and "Hi!" would be red.
This is my not working code:
<script type="text/javascript">
function post()
{
var preview = document.getElementById("preview");
var submit = document.getElementById("post");
var text = submit.value;
<?php str_replace("red:*:",'<i class="red">*</i>',text); ?>
preview.value = text;
}
</script>
You have at least two massive problems here.
You can't str_replace with wildcards like you are (the asterisks you use are just that - the asterisk character, not a placeholder).
Your idea of the page-rendering process is off - you can't just call some PHP code in JavaScript and have it update the page. Any PHP code will be executed and printed when your page is generated on the server - it can't interact with the page like JavaScript can (JS can because it is executed within the browser, but the browser never actually sees your PHP code as you can check by going to View->Source and seeing what you see). You certainly cannot reference a JavaScript variable from PHP.
Two options.
Option 1 - Proper Server-Side
if you want to colour objects on page load based on post, do something like this:
<?php
# If the value was posted
$raw = isset($_POST['userstring']) ? $_POST['userstring'] : "";
# Split it based on ':'
$parsed = explode(':', $raw);
$colorClass = "";
$text = "";
if (count($parsed) >= 2)
{
$colorClass = $parsed[0];
$text = $parsed[1];
}
?>
<form action="" method="post">
<input type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
<?php if (strlen($text) > 0) { ?>
<i class="<?php echo $colorClass; ?>">
<?php echo $text; ?>
</i>
<?php } ?>
</div>
Option 2 - Proper Client-Side
Include jQuery in your <head> tag to make your life easier. If you really don't want to include jQuery you can still change the jQuery calls to your getElementById etc. (you'll want to replace the html() call with '.innerhtml' I think - just look it up).
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
function post() {
var split = $('#userinput).val().split(separator, limit)
if (split.length >= 2) {
var color = split[0];
var text = split[1];
$('#preview').html('<i class="' + color + '">' + text + '</i>');
}
return false; // Stop form submit
}
</script>
<form action="" method="post" onsubmit="post()">
<input id="userinput" type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
</div>
</body>
You're mixing server and client side technologies here. The code in the php lock is evaluated once (while still on the server). You're looking for something that will operate entirely on the client side.
This means you need to look into Javascript regular expressions, instead of PHP preg_match type stuff.
http://www.regular-expressions.info/javascriptexample.html
You're looking for this type of thing:
stringObject.replace( regularExpressionVarOrLiteral, replacement );
Josh

Categories