Insert value in DB with form on a barcode scanner - javascript

I have a Datalogic Barcode Scanner Falcon 4410. I have a html form on it to add products into a database.
Here is my simple form :
<form id="formprod" class="form-horizontal" method="post" action="url">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Référence</label>
<div class="col-md-4">
<input id="textinput" name="reference" type="text" placeholder="placeholder" class="form-control input-md">
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<div class="col-md-8">
<input type="submit" id="button1id" name="submit" value="OK" class="btn btn-success"/>
<input type="reset" id="button2id" name="button2id" value="RESET" class="btn btn-danger"/>
</div>
</div>
</fieldset>
</form>
So, in the barcode scanner if I open my html page, write with virtual keyboard in input and submit with submit button: it works.
But if I'm scanning a barcode, form is automatically submitted, record is saved but reference field is empty in DB.
My PHP code :
<?php
if(isset($_POST["reference"])){
$hostname='****';
$username='****';
$password='*****';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=name",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO product (reference)
VALUES ('".$_POST["reference"]."')";
if ($dbh->query($sql)) {
echo 'Done!';
}
else{
echo 'Error!';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Do you have an idea?
Thanks.
PS : It's not optimized for SQL injection for example, it will be done when record will work
EDIT : WORK AFTER A REBOOT.

Most barcode scanners I've used in libraries send a carriage return following the data they've scanned. There is often a way to declare that you don't want a CR in the scanner's settings. Check the manufacturer's website.

Related

Send data to PHP Class and post in in SQL database

I am quite new in PHP and all web development. I am wondering if someone could help me with data flow. I am trying to send form data to a PHP file and then call the function from the class to send data to the sql database. Right now, I don't have any PHP extensions in VS Code so I could debug it and see what is not working. And ofcourse in DOM there is only JS file and PHP which holds HTML code.
This is my code in JavaScript where it takes all user given data and sends it to php. But in form it consists of three static inputs, and then there is a switcher, which displays a user defined view.
`
//Function check for correct input with .value() call
//If it returns 'true' it proceedss with further validation of additional fields that change dynamically.
//When all fields have passed validation function begins to POST FormData to PHP file for backend work.
if(validate.test(sku) && validate.test(name) && validatePrice.test(price)){
if(validateAdditional(this.switcher)){
let xml = new XMLHttpRequest();
xml.open("POST", "./backend/product.php", true);
xml.onload = () => {
if(xml.readyState == 4 && xml.status == 200){
let response = xml.response;
alert(response);
form.reset()
history.back();
}
};
let formData = new FormData(form);
xml.send(formData);
}
}else{
alert("Please check if there is not any spaces or special characters added");
}
}
Then I created a class that will hold all of the network calls to post/read/edit/delete data from the sql database.
class DatabaseCalls{
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "scandiweb";
public function insertData($dataQuery){
$connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if(!$connection){
return die("Connection failed" . $connection->connect_error);
}
if($connection->query($dataQuery)){
return "Done";
}else{
echo "Error: " . $dataQuery . "<br>" . $connection->connect_error;
}
$connection->close();
}
}
And then where there are model call network functions to send it to sql. JS file post data to models file. And then procedurally create the Product object and call the first function where I populate the input data.
<?php
include("netowking.php");
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$memory = $_POST['dvd-memory'];
$dvdProduct = new Product($sku, $name, $price, $memory);
echo $dvdProduct->insertQuery();
class Product extends DatabaseCalls{
private $sku;
private $name;
private $price;
private $memory;
public function __construct($sku, $name, $price, $memory){
$this->sku = $sku;
$this->name = $name;
$this->price = $price;
$this->memory = $memory;
}
public function insertQuery(){
$sql = "INSERT INTO dvd (SKU, Name, Price, Memory)
VALUES ('$sku', '$name', '$price', '$memory')";
$response = $this->insertData($sql);
return $response;
}
}
And for context I will all also HTML code.
<form class="input" name="input">
<div>
<label for="sku">SKU:</label>
<input id="sku" type="text" name="sku" placeholder="#SKU">
</div>
<div>
<label for="name">Name:</label>
<input id="name" type="text" name="name" placeholder="#name">
</div>
<div>
<label for="price">Price ($):</label>
<input id="price" type="text" name="price" placeholder="#price">
</div>
<div class="switcher">
<h3>Type Switcher</h3>
<select name="select" id="select">
<option selected disabled>Choose a type</option>
<option value="dvd">DVD</option>
<option value="furniture">Furniture</option>
<option value="book">Book</option>
</select>
</div>
<div class="switchContent">
<div class="dvd-mem", id="dvd">
<p>DVD-disc</p>
<label for="dvd-memory">Size(MB):</label>
<input id="dvd-memory" type="text" name="dvd-memory" placeholder="Please enter MB amount here">
<p>Please enter amount of disc memory in MB.</p>
</div>
<div class="furniture" id="furniture">
<p>Furniture</p>
<div>
<label for="height">Height(CM):</label>
<input id="height" type="text" name="height" placeholder="Enter height in here">
</div>
<div>
<label for="width">Width(CM):</label>
<input id="width" type="text" name="width" placeholder="Enter width in here">
</div>
<div>
<label for="lenght">Height(CM):</label>
<input id="lenght" type="text" name="lenght" placeholder="Enter lenght in here">
</div>
<p>Please enter all dimensions of furniture</p>
</div>
<div class="book" id="book">
<p>Book</p>
<label for="weight">Weight(KG):</label>
<input id="weight" type="text" name="weight" placeholder="Please enter weight in KG">
<p>Please enter weight of book</p>
</div>
</div>
</form>

How to make onkeyup works in next row?How to make Javascript works in next row?

I Make CRUD with Php and success.
as usual for show data PHP use while looping.
In the Edit action I used Popup/Modal didn't make a new page for edit, actually my Edit was running smoothly.
But I have a problem with JavaScript for function automatically, when one form/field is filled, the other form/field is filled (actually only one field is automatic).this automatic problem only works on the first row edit action (works smoothly) but on the next row automatically does not work
Javascript doesn't work in while looping, it only works on the first loop, the next loop doesn't work.
I have done various automation methods with Javascript but the results are the same, only Edit the first row, the next row doesn't work. did I do something wrong?
CODE JS(Javascript)
<script type="text/javascript">
function Sremarks() {
if ($('#result').val() != 0) {
var input = parseInt(document.getElementById('input').value);
var result = parseInt(document.getElementById('result').value);
if(input < result){
document.getElementById('remarks').value = "bad";
}else{
document.getElementById('remarks').value = "Good";
}
} else{
document.getElementById('remarks').value = "0";
}
}
</script>
CODE PHP and HTML
here I am using onkeyup = "Sremarks ()" to pass to Function Js like in line Form/Field Edit Input and result
<form action="editmhs.php" method="post" enctype="multipart/form-data">
<!-- Open Php While Looping -->
<?php
$id = $pecah['id'];
$query_edit = mysqli_query($koneksi, "SELECT * FROM axle1 WHERE id='$id'");
while ($row = mysqli_fetch_array($query_edit)) {
?>
<!-- Form/Field Id hidden -->
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<!-- Form/Field Edit Input -->
<div class="form-group">
<label>Input</label>
<input type="number" name="input" id="input" class="form-control" min="0" max="100" value="<?php echo $row['input']; ?>" onkeyup="Sremarks()">
</div>
<!-- Form/Field Edit Result -->
<div class="form-group">
<label>Result</label>
<input type="number" name="result" id="result" class="form-control" min="0" max="100" value="<?php echo $row['result']; ?>" onkeyup="Sremarks()">
</div>
<!-- Form/Field Edit Remarks -->
<div class="form-group">
<label>Remarks</label>
<input type="text" name="remarks" id="remarks" class="form-control" value="<?php echo $row['remarks']; ?>" readonly>
</div>
<!-- Button submit and Close -->
<div class="modal-footer">
<button type="submit" name="upload_ubah" value="Upload" class="btn btn-success">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<!-- Close PHP While Looping -->
<?php
}
?>
</form>

theme php contact form

I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});

PHP Prevent Re submission for multiple forms on same page

Hi have checked answer from this page: But it uses action="" is it vulnerable to XSS attacks? If yes then without such solution what are my options?
I tried using header redirect. But as I have 2 forms,(in some pages 4-5 forms) header re direction is not working for me with errors.
Here is my code: (Simplified)
1st form: works ok with a redirect.
<form name="ip_block" method="post" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default"
name="ip_block_add">Submit</button>
</div></div>
</form>
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
header("refresh:5;url=./admin-security.php");// avoiding form
resubmission
echo 'Added successfully';
}
else {
echo 'failed to insert';
}
}
?>
Form 2:
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<button type="submit" class="btn btn-warning">Clean Data</button>
</form>
<?php
if(isset($_POST['data_clear'])){
if($mysqli->query("CALL clear_old_data")){
header("refresh:5;url=./admin-security.php");// avoiding form resubmission
echo 'operation successfull';
}
else
{
echo 'database failure';
}
}
//----
?>
For Second form I get error like this
Warning: Cannot modify header information - headers already sent by
For 2nd form I am using header before echo still it doesn't work.
reference, I tried with javascript too but that failed.
echo "<script>setTimeout('window.location.href='./admin-
security.php';',4000);</script>";
Updated with Dainis Abols idea: but form re submit option is still showing on page refresh
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<?php
$var=111;
$_SESSION['var']=$var;
?>
<input type="hidden" value="<?php echo $var; ?>" name="varcheck"
/>
<button type="submit" class="btn btn-warning">Clean
Data</button>
</form>
<?php
if(isset($_POST['data_clear']) &&
($_POST['varcheck']==$_SESSION['var'])){
// Some code
}
I'd rather use ajax to send data to the database, without form submiting, and on success I would use js to redirect to /admin-security.php. In this case it's not possible to send the data twice.
Here is the PHP Code:
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
HTML:
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
And AJAX written with JQuery
<script>
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
alert("Done");
location.href = "./admin-security.php";
}
else alert("Fail!");
}
});
}

Check if input field empty

I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.

Categories