I have this code for search in my database, I use a barcode scanner (work like a keyboard), when I scan a barcode the input text shown perfectly, but I need to press MATCH to do the enter function, I want to submit it automatically after the barcode scanner scan a code and not to press MATCH.
<html>
<body>
<div class="container pt-5">
<div class="row">
<form method="POST" action="match.php" autocomplete="off">
<div class="form-group">
<label>Scan:</label>
<input type="text" id="no" name="no" class="form-control" required>
</div>
<div ></div>
<button class="btn btn-info" name="sub" type="submit">MATCH</button>
</form>
</div>
</div>
</body>
</html>
<?php
include 'includes/conn.php';
if (isset($_POST['sub'])) {
$sca=trim($_POST['no'],"");
$flag=0;
$credentials="";
$password="";
$firstname="";
$lastname="";
$new2 ="SELECT * FROM `voters`";
$res2=mysqli_query($conn, $new2);
while($row=mysqli_fetch_array($res2)){
//echo $row['number'].'<br>';
// if($row['number']){
if($row['credentials'] == $sca){
$flag=1;
$credentials=$row['credentials'];
$password=$row['password'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}if ($flag==1) {
echo "<div class='container'><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'><div class='alert alert-success d-flex justify-content-center mt-3'>".
'<br><b>Votante:</b>'.' '.$id.
'<br><b>Registro:</b>'.' '.$credentials.
'<br><b>Contraseña:</b>'.' '.$password.
'<br><b>Nombre:</b>'.' '.$firstname.
'<br><b>Apellidos:</b>'.' '.$lastname.
"</div></div></div><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'>" ;
return;
}
else{
echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>";
return;
}
}
mysqli_close($conn);
?>
We had to work with barcode scanners a while ago, where we had a similar request, so I hope I can help here. Most simple barcode scanners just enter the scanned code and append a new line.
As stated in the comments you need some JavaScript in order to do that. We used the jquery library. Like CBroe said, you need to find the correct event, to use. We tried different events and found the "change" event to be the best suitable one for us.
Our case was a little more complex, because we had multiple fields and had to make ajax requests, so I tried to reduce our script to something that may be a good starting point for you:
$(document).ready(function() {
$('#no').change(function () { //if content of field with id #no changes do stuff
let value = $(this).val();
const minlength = 5;
if (value.length >= minlength) {
$( "#scanform" ).submit(); //submit form with id scanform
}
});
});
Pleas note, that this script assumes you add the id "scanform" to your form tag.
Related
Good Day!
I am having a difficulty when it comes to showing a pop-up box in my webpage. I would like to show it when it meets a certain condition inside my php code, which is under the Condition.php. I have included the js file, which removes a certain class to make the box visible. How would I execute the JS code inside the Condition.php when it meets a certain condition?
Here are my codes:
Condition.php
<?php
// Defined variables and additional codes section
if (strlen($str) == 4) {
// Show the popup box
}
// Additional Codes
?>
ConfirmCheck.js
$(document).ready(function () {
$('#confirm').click(function () {
$('.popup').removeClass("hide");
});
});
Check.php
<form class="frm" action="Condition.php" method="POST">
// Additional Codes here
<input type="submit" name="checkOutBtn" value="CONFIRM" id="confirm">
</form>
<?php include 'box.php';?>
<script src='ConfirmCheck.js'></script>
Box.php
<div class="popup hide" id="popupID">
<div class="box">
<div class="form">
<h1>SUCCESS!</h1>
<form action="home.php">
<div class="form-group">
<p class="paragraph">
Your order has been successfully placed!
</p>
<button class="homepageBtn" onclick="home.php">GO TO THE HOME PAGE</button>
</div>
</form>
</div>
</div>
</div>
To do what you require simply put the if condition inside box.php and remove condition.php as it serves no purpose having an entire PHP page for a single condition.
box.php
<div class="popup <? if (strlen($str) != 4) { ?>hide<? } ?>" id="popupID">
<div class="box">
<div class="form">
<h1>SUCCESS!</h1>
<form action="home.php">
<div class="form-group">
<p class="paragraph">
Your order has been successfully placed!
</p>
<button class="homepageBtn" onclick="home.php">GO TO THE HOME PAGE</button>
</div>
</form>
</div>
</div>
</div>
I guess the problem is that you've set the action of your form to Condition.php but included the box design and code on check.php.
Note that #confirm is and input of type submit so after its pressed it will redirect you to the page specified at the action of the form.
I can suggest two possible fixes to that:
[least suggested] display the confirmation box on the Condition.php page
[most suggested] use AJAX!
The first fix requires you to move the markup and styles for box to the Condition.php file and design a whole confirmation/post action page
The second fix is better because by sending the Data to the server using AJAX you're not only going to stay on the same page (check.php) but you can also sort of hide the address to Condition.php which is supposed to be a backend file(from what i understood)
The structure should look something like this:
check.php:
<div class="frm">
// Additional Codes here
<buttin name="checkOutBtn" id="confirm">CONFIRMM</button>
</form>
<?php include 'box.php';?>
<script src='ConfirmCheck.js'></script>
ConfirmCheck.js:
$(document).ready(function () {
$('#confirm').click(function () {
// code to get all of your fields and put them in a js object: FDATA
$.ajax({type:'POST', url:'Condition.php', data: FDATA,
success:function(){
$('.popup').removeClass("hide");
}});
});
});
Condition.php:
<?php
// Defined variables and additional codes section
if (strlen($str) == 4) { //success
echo "success message";
}else{ // failed
header('HTTP/1.0 400 Bad Request');
die("bad request");
}
// Additional Codes
?>
The request goes back and forth between check.php and Condition.php in the background and your code gets notified through a callback whether or not to show the box.
For my login form firefox saves but chrome not prompting the "save password" box. I have tried by adding autocomplete="on" but it is not working. Can any one suggest me the answer. I didn't want to use any extention.My code is given below.
<form spellcheck="false" autocomplete="on" id="login-form" action="/user/login/do-login" method="post">
<div class="separator-bar"></div>
<div class="credentials-container">
<div class="username-container">
<div class="label">Email/Username: </div>
<div class="field">
<input class="wx-input" type="text" name="<?php echo $this->escape(App_Api_User::ARG_USERNAME)?>" value="<?php if(isset($this->username)) {echo $this->username;}?>" spellcheck="false"/>
</div>
</div>
<div class="password-container">
<div class="label">password: </div>
<div class="field">
<input class="wx-input" type="password" name="<?php echo $this->escape(App_Api_User::ARG_PASSWORD)?>"/>
</div>
</div>
</div>
<div class="separator-bar bottom"></div>
<div class="forgot-password-container">
<div class="text">forgot password: </div>
<div class="password-page button"><a class="loginForgotPassword" href="#">CLICK HERE</a></div>
</div>
<div class="submit-container">
<input class="login button disabled" type="submit" name="submit" value="GO" />
</div>
<div id="infoMessageContainer">
</div>
<div class="general-error"></div>
</form>
$('body').on('click', '.submit-container .login', function(e) {
if ($(this).hasClass('disabled')) {
e.preventDefault();
e.stopPropagation();
}else{
var self = this;
self.submit();
}
});
_success: function()
{
window.location.href = '/user';
}
All browsers use heuristics for knowing when to save passwords. I'm familiar with Firefox and Chrome. The heuristic they use seems to be:
The form must have a password field
The text input just before the password field is assumed to be the user name
Only those two input fields are saved. Firefox then prompts you that
it can remember your changed password when you fill out a form with two password fields.
Here is a list of things that I typically see break these algorithms:
Sites that use autocomplete=off (specifically requesting that
browsers not remember passwords)
Separating login into multiple pages where the user name is entered on one page and the password is entered on the next.
Using Javascript to copy the contents of these fields into hidden
fields in a hidden form and then submitting the hidden form rather
than the visible form
Requiring more than two fields to be filled out such as
User name, SSN, and password
Username, password, and PIN
Changing the names of the username and password fields
periodically (causes firefox to no longer be able to fill in the
password, even when it is remembered).
I have made lots of changes and then finally works with below block of code.
Hope it will help someone. You need to submit form with this code.
var winNav = window.navigator,
isIOSChrome = winNav.userAgent.match("CriOS");
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
//Use below if statement, if you want to run only in chrome
if(isChrome || isIOSChrome){
$('#login-form').submit(function () {
if(-1 !== this.action.indexOf('/login')) {
var jForm = $(this);
$.post(this.action, $(this).serialize(), function (data) {
if (data.success == true) {
jForm[0].action = '/user';
jForm.submit();
}
});
return false;
}
});
}
Does anyone know about a good tutorial where submiting a form from a sing page is explained? I have a few page views in my html code and one of them is a form with three fields (Name, Email and Message) what I am trying to achieve is to submit the form data via Ajax without using a process.php directly.
This is the Form:
<section class="hidden" id="view-forms">
<header>
<button class="left arrow" data-vin="view-home" data-sd="sr">
<div class="label">All Contacts</div>
</button>
<h1>Message</h1>
<button class="right bold green" data-vin="view-done" data-sd="sl">
<div class="label">Send</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<input placeholder="Name" type="text" />
<input placeholder="Email" type="email" />
<textarea placeholder="Your Message" rows="5"></textarea>
</div>
</div>
</div>
</section>
This is the confirmation page after message has been sent:
<section class="hidden" id="view-done">
<header>
<h1>That's it!</h1>
<button class="right bold" data-vin="view-home" data-sd="popout">
<div class="label">Done</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<h2>Message sent!</h2>
</div>
</div>
</div>
</section>
Please, let me know if any of you have already implemented something like this. Thank you.
You could submit to the same PHP page. You just need an if statement to separate the code that generates the page from the code that submits your form. That being said, you should probably just create a second PHP script to handle the form submission. If you wanted to implement it using the if statement, I would add a piece of information to your GET/POST request which would be something like:
'formSubmission='+true
Okay, for the more details, look at this tutorial, it goes over the basics. In your case, try this (NOTE: I haven't tested any of this). Also, add an ID to each of the elements (I assumed they would be the same as your current name attributes and that the textarea would have the ID message).
function()submitForm(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
var requestData = 'name='+name+'&email='+email+'&message='+message+'&formSubmission='+true;
//I'm assuming that you're using a POST request (this depends on the length of the message
var AJAXObj = new XMLHttpRequest();
//don't forget to replace currentURL.php with the name of the page that will handle the submission
AJAXObj.open('POST', 'currentURL.php', true);
AJAXObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
AJAXObj.send(requestData);
AJAXObj.onreadystatechange = function (){
var AJAXObj = event.target;
if(AJAXObj.readyState == 4 && AJAXObj.status == 200){
var responseText = AJAXObj.responseText;
//things that you might want to do with your responseText
}
}
}
Now here's the PHP:
if(isset($_POST['formSubmission'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//code that handles the form data that has now been passed to PHP
}
Just a thought, don't submit to the same PHP page that you're currently on. Create a new file and paste the code into that. It'll be cleaner.
<div class="accordion" id="accordion2">
<?php $info= mysql_query("SELECT id, title, description FROM event"); ?>
<?php while ($row = mysql_fetch_array($info, MYSQL_NUM)): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse<?php print $row[0]; ?>"><?php print $row[1]; ?></a><span class="delete" id="<?php print $row[0]; ?>">×</span>
</div>
<div id="collapse<?php print $row[0]; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<div class="row-fluid">
<div class="span6">
<?php print $row[2]; ?>
</div>
<div class="span6 ppl">
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
I have a pretty simple way of printing out my twitter bootstrap accordion.
I have this displayed on my page and I also have a form on top of the accordion itself from where I can submit another one into the database using ajax. Here is the form:
<form class="form">
<fieldset>
<legend>Stuff</legend>
<input class="class1" type="text" placeholder="xx">
<input class="class2" type="text" placeholder="xx">
<input class="class3" type="password" placeholder="xx">
<textarea maxlength="320" rows="5" class="class4" placeholder="xx"></textarea>
<div class="submit btn">Add</div>
</fieldset>
</form>
Here is the jQuery:
$(".form .submit").bind("click", function() {
var title = $(".form input.class1").val();
var email = $(".form input.class2").val();
var stuff1 = $('.form input.class3').val();
var stuff2 = $('.form textarea.class4').val();
if (title && email) {
var data = {title: title, email: email, stuff1: stuff1, stuff2: stuff2};
$.post("action.php", data, function() {
$(".form input, .form textarea").val("");
alert('done');
});
}
else {
alert('something went wrong');
}
});
And finally my action.php file:
<?php require('access.php');
if ($_POST['title'] && $_POST['email']) {
$title = $_POST['title'];
$email = $_POST['email'];
$stuff1 = $_POST['stuff1'];
$stuff2 = $_POST['stuff2'];
mysql_query("INSERT INTO events (title, email, stuff1, stuff2) VALUES('$title', '$email', '$stuff1', '$stuff2')");
}
Everything works, but like the title says, I want the information entered to be prepended to the accordion div as a new accordion group (without refreshing the page). My brain refuses to work with me on this, since to me it seems that if I submit the values, I have to make another request to the database to get the freshly generated id of the new event to have my accordion layout working.
Wat do?
And sorry for using a deprecated way of using mysql :O
So mysql functions aside, all you are looking to do is to prepend some html to an element. You already have a callback function on your post and so all you need to do is to make it actually do something i.e.
$.post('action.php', data, function() {
var newID = 123; // get this from the response text
$('div.accordion-inner').prepend('<div class="row-fluid"><div class="span6">'+newID +'</div><div class="span6 ppl"><ul></ul></div></div>');
});
This will attempt to prepend the div as specified to div.accordion-inner
Just replace the prepended with whichever html you are looking for.
And as an additional note, http://php.net/manual/en/function.mysql-insert-id.php will get you the PRIMARY KEY value for the last INSERT performed on your MySQL connection
I am using jQuery (version 1.8.1) with PHP (version 5.3) to submit a form adding an entry into a mySQL database, what is happening is on the first submit everything is fine but for each subsequent submission without a page refresh it adds an additional entry.
In addition I'm also using Bootstrap (version 2.1.1) and the upload widget from Jasny for Bootstrap (version j1a) in the UI. I have not yet connected the upload widget to the processing or submit as I detected the duplication problem when I was implementing it.
Please note that this is a proof of concept system so the code is rough as I'm not going to invest in cleaning it up until the project is confirmed. Due to this, you will notice some inline mySQL queries, I know that this isn't the best way to do it however it works for the purpose of demonstration and will be cleaned up later. Also as a POC system it is on an internal server currently, I can share the code but cannot show an example site at this time unfortunately.
Now back to the issue, as an example, the first post for "Company 1" has 1 record added for "Company 1", the second record for "Company 2" adds 2 records for "Company 2", the third record for "Company 3" adds 3 records for "Company 3" and so on. If I reload the form page in any way (refresh or a new request) the problem restarts from the first submission.
I am using jQuery serialize with ajax to post the data to the PHP processor. I have logged all of the posts being received by the processor and I see the processor is receiving multiple records from the form, I thought it may have been caused by a foreach loop in the PHP but this is not the case.
I have removed the jQuery functions and it works perfectly each time without any duplicates on normal PHP submit.
I have manually processed the entries via jQuery instead of serialize but as there is a dynamic array via PHP I still used serialize on that array, this produced the duplicates as described above.
I have searched the issue for a number of days but cannot find anything definitive to clear up the issue, all suggestions on blogs and forums that looked to be related did not work, I have tried around 10-15 different options.
The combination of all of this leads me to believe the issue is coming from the jQuery serialize and/or ajax functions but my eyes have become glazed each time I look at this code now.
I am also considering placing the form in an external file and reloading it fresh via ajax or cleaning the form setting it back to defaults via jQuery for each new entry required however I do not believe either of these approaches will solve the problem.
Any help is greatly appreciated, thanks in advance for the help!
jQUERY code
<script>
$(document).ready(function() {
$('.fileupload').fileupload('name:logo');
$('.help-inline').hide();
$("#btn_process").click(function() {
$('form').submit(function() {
$('.help-inline').hide();
var company_name = $("#company_name").val();
if (company_name === "") {
$("div#name_group").addClass("error");
$("span#name_error").show();
return false;
}
var dataString = $('form').serialize();
$.ajax({
type: "POST",
url: "inc/addcompany.php",
data: dataString,
success: function(html) {
if(html === 'success')
{
$('#message')
.addClass("label label-success")
.css("margin-bottom","20px")
.html("<h3>Login successful</h3><p>Company added</p>")
.slideDown(1500, function() {});
}
else
{
$('#message')
.addClass("label label-important")
.css("margin-bottom","20px")
.html("<h3>Error</h3><p>There was an error, please check the information and try again</p>")
.slideDown(1500, function() {});
$("div#name_error").addClass("error");
$("span#name_error").show();
$("div#type_error").addClass("error");
$("span#type_error").show();
return false;
}
}
});
return false;
});
});
});
</script>
HTML markup
<form class="form-horizontal" id="add_company" method="POST" action="">
<fieldset>
<div id="message"></div>
<div id="name_group" class="control-group">
<label class="control-label" for="company_name">Company name </label>
<div class="controls">
<input type="text" id="company_name" name="company_name" />
<span id="name_error" class="help-inline">This needs to be more than 3 characters</span>
</div>
</div>
<div id="type_group" class="control-group">
<label class="control-label">Company type </label>
<div class="controls">
<?
$sql = "SELECT description,id FROM types ORDER BY description";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
while($company_type = mysql_fetch_array($qry)) {
echo '
<label class="checkbox inline"><input type="checkbox" name="type[]" value="'.$company_type['id'].'" /> '.$company_type['description'].' </label>';
}
?>
<span id="type_error" class="help-inline">Please select a minimum of 1 type</span>
</div>
</div>
<div id="website_group" class="control-group">
<label class="control-label" for="website">Website </label>
<div class="controls">
<input type="text" id="website" name="website" placeholder="www.something.com" />
</div>
</div>
<div id="logo_group" class="control-group">
<label class="control-label">Logo </label>
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 50px; height: 50px;"><img src="/img/50x50.png" /></div>
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 50px; height: 50px;"></div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span>
<span class="fileupload-exists">Change</span>
<input type="file" /></span>
Remove
</div>
</div>
</fieldset>
<input type="hidden" name="action" value="add_company" />
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" name="btn_process" id="btn_process">Save changes</button>
</form>
The PHP processor
$error = false;
$error_company_name = false;
$error_type = false;
$error_website = false;
$company_name = $_REQUEST['company_name'];
$type = $_REQUEST['type'];
$website = $_REQUEST['website'];
$logo = $_REQUEST['logo'];
if(empty($company_name)) {
$error = true;
$error_company_name = true;
}
include_once('db.php');
$sql = "SELECT description,id FROM company_types";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
$type_count = 0;
while($array = mysql_fetch_array($qry)) {
$type_count = $type_count+1;
}
if($type_count == 0) {
$error = true;
$error_type = true;
}
$ic = 0;
foreach($_REQUEST['type'] as $item) {
$ic = $ic+1;
}
if($ic == 0) {
$error = true;
$error_type = true;
}
if(isset($website) && $website != ' ') {
$url = 'http://'.$website;
if(!filter_var($url, FILTER_VALIDATE_URL)) {
$error = true;
$error_website = true;
}
}
if($error == false) {
$sql = "INSERT INTO company_list (name,website,logo) VALUES('$company_name','$website','$logo')";
$qry = mysql_query($sql) or die ("ERROR: could not add company => ".mysql_error());
$company_id = mysql_insert_id($link);
if($company_id == '' || $company_id == null || empty($company_id)) {
echo 'fail';
exit;
}
foreach($_REQUEST['type'] as $company_type) {
$sql = "INSERT INTO companies_types (companies_id,type_id) VALUES('$company_id','$company_type')";
$qry = mysql_query($sql) or die("ERROR: could not link company type: => ".mysql_error());
}
echo 'success';
}
Add $('form').unbind('submit'); immediately above this line: $('form').submit(function().
I found this solution here: https://stackoverflow.com/a/668354/300575
Note: I verified that this works by copying your code and testing it on my server.
It may be a patch and dont know if it will work but there is a jQuery ajaxStop which can be called at the success call back.