i'm making an online barcode scanner application and having some issues with sending a javascript variable to php for my query , and getting it back in my html file with the data.
User scans barcode (studentNr)
studentnr --> variable is going to be posted to the php file.
in php file : query to compare with variable
result of query --> back to the parameter of function(data)
print result.
Sounds easy, but how do I do this correctly?
Index.html :
<head>
<meta charset="utf-8" />
<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width" />
<script src="javascripts/jquery.js"></script>
</head>
<body>
<div>
<input type="text" name="barcode" id="barcode"> // BARCODE SCAN
<input type="text" id="student" placeholder="studentenNaam" size="30"> //NAME FROM DB
<!-- <input type="text" id="barcode" placeholder="Waiting for barcode scan..." size="40">
<input type="text" id="student" placeholder="studentenNaam" size="30">-->
</div>
// just the script for scanning the barcode :
<script>
var barcodeParsed = null;
var studentenNr = null;
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
barcodeParsed = barcode;
var barcodeParsing = barcodeParsed.substring(5,11);
$("#barcode").val("s" + barcodeParsing);
studentenNr = "s" + barcodeParsing;
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
$.post('testdb.php', {'studnr' :studentenNr}, function(data){ //POST JS VAR TO PHP FILE
$('#student').html(data); //RECEIVE DATA FROM DB INTO ID ELEMENT
});
e.preventDefault();
}
});
</script>
</body>
And in my testdb.php file it looks like this :
<?PHP
$studnr = htmlspecialchars($_POST['studnr']);
if(isset($studnr)){
$user_name = "root";
$password = "";
$database = "Student";
$hostname = "127.0.0.1";
$db_handle = mysql_connect($hostname, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM student where studentenNr= '$studnr'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
/* Here needs the data to fetch*/
print $db_field['naam'] . "<BR>";
print $db_field['studentenNr'] . "<BR>";
print $db_field['voornaam'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
The problem is i can't receive any data from my html file in to my php file, plus i don't know how i can put the received data back in to my html file.
in the php-file..How do I write it back to the html ?
Do I need to use Ajax,Jquery,..
Any other solutions ?
Thank you for helping me out !
UPDATE
when adding this between the if(db_found) brackets I get an Internal Server Error 500.
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
$sql->execute($arraytest = array(':studnr' => studentenNr,naam );)
$sql->execute(array(":studentenNr" => $studnr));
$data = $sql->fetchAll();
foreach($item as $data){
print($item["naam"]);
log($item["naam"]);
On your javascript you're sending studnr parameter:
$.post('testdb.php', {'studnr' :studentenNr}, function(data){
In your php script you trying to get the value from studentenNr parameter:
$studnr = htmlspecialchars($_POST['studentenNr']);
You need to cahnge your script to
$studnr = htmlspecialchars($_POST['studnr']);
Edit:
You're getting internal error because of this line:
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
You need to prepare the SQL statement with the parameters and then bind them, so the line should be (something like):
$sql = $db->prepare("select * from student where studentenNr= :studnr");
$sql->execute(array(':studnr' => $studnr ));
Related
I have got a table 'famille'
CREATE TABLE famille (
idf INTEGER(6) NOT NULL ,
>>>>>> nomf VARCHAR(40) NOT NULL,
CONSTRAINT pk_famille
PRIMARY KEY (idf),
>>>>>> CONSTRAINT un_famille_nomf
>>>>>> UNIQUE (nomf)
)ENGINE = InnoDB, DEFAULT CHARACTER SET utf8; <<<<<<<<<
When adding a new 'famille', i have to check constraints : the unique constraint refer to a text field.
Examples :
idf nomf
100 Actinidiacées
110 Aizoaceae
120 Amaranthacées
130 Amaryllidacées (Liliacées)
140 Apiacées (Ombellifères)
...
I use asynchronous query Javascript/Php to check values in a form that enable to add a new 'famille' and that the value of the field 'fnom' in the form already exists in the table : when le input field is not accentuated, it works, but when there are accentuated characters, it does not work : the form is submit and I get a normal SQL error.
Form simplified :
<html><head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta charset="utf-8" /> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<title>Gestion - Administration du site</title>
...
<link rel='stylesheet' href='main.css' type='Text/css'>
<script src="js/checkfamille.js?dev=1574345195"></script>
</head>
<body><h2 class='entete'>Les familles</h2>
...
<form name='frmNewfamille' id='frmNewfamille' method='post' ><fieldset id='fs1'><legend><b>Informations</b></legend><div class='ligne'><span class='label'><label for='fidf'>Identifiant</label></span><span class='champs'>
<input type='number' size='6' minlength='6' maxlength='6' name='fidf' id='fidf' required value='' /></span>
</div><div class='ligne'><span class='label'><label for='fnomf'>Intitulé</label></span><span class='champs'>
<input type='text' size='40' minlength='40' maxlength='40' name='fnomf' id='fnomf' required value='' /></span></div></fieldset><fieldset>
<input type="hidden" id="valide" name="valide" hidden />
<input class='bouton' type='button' name='btnNewAfamille' id='btnNewAfamille' value='Ajouter'
onclick='return checkfamille();' />
>>>>>>>>>>>>>>>>>>>^^^^^^^^^^^
</fieldset>
</form>
...
Javascript :
function checkfamille()
{
var idf = document.forms["frmNewfamille"]["fidf"];
var nomf = document.forms["frmNewfamille"]["fnomf"];
// somme checks
...
// ajax call
...
return checkFamilleAjax('code.php?idf='+escape(idf.value)
+'&nomf='+escape(nomf.value) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+'&mode=insert');
...
function checkFamilleAjax(fichier, nom)
{
var xhr_object;
if(window.XMLHttpRequest) // FIREFOX
xhr_object = new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
else
return(false);
xhr_object.onreadystatechange = function() {
if (xhr_object.readyState == 4 && (xhr_object.status == 200 || xhr_object.status == 0)) {
var reponse = (xhr_object.responseText).replace(/\s/g, "");
if(reponse=="0") {
document.getElementById("valide").value = "true";
document.forms["frmNewfamille"].submit();
return true;
} else if(reponse=="1") {
// set error fields on the form
....
}
}
xhr_object.open("GET", fichier, true);
xhr_object.send(null);
}
PHP code :
<?php session_start();
// includes
...
$database = new Database();
$famille = new Famille($database);
try {
if ($mode == 'insert') {
if (isset($_GET["idf"]) && isset($_GET["nomf"])) {
// checks if number already exists
$database->query('SELECT idf FROM famille WHERE idf = :id;');
$database->bind(':id', $_GET["idf"]);
if ($result = $database->execute()) {
if ($database->rowCount() >0) {
echo "1"; exit;
}
} else {
echo "7 ". $database->getError(); exit;
}
// checks if name already exists
$database->query('SELECT idf FROM famille WHERE nomf = :lname;');
$database->bind(':lname', $_GET["nomf"]);
if ($result = $database->execute()) {
if ($database->rowCount() > 0) {
echo "2"; exit;
}
} else {
echo "8 ". $database->getError(); exit;
}
echo "0"; exit;
} else {
echo "9"; exit;
}
...
Here is the value of $_POST from my form :
Array ( [fidf] => 3214 [fnomf] => Rosacées [valide] => true )
and here is the query error :
Erreur SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate
entry 'Rosacées' for key 'un_famille_nomf'
I have checked
- all sources files : utf8 OK
- the database data
- php/mysql connexion parameters and code :
define("DB_HOST", "localhost");
define("DB_USER", "xxxx");
define("DB_PASS", "xxxx");
define("DB_NAME", "xxxx");
define("DB_CHARSET", "utf8");
and a database class :
class Database
{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $charset = DB_CHARSET;
private $dbh;
private $error;
private $stmt;
public function __construct(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname. ';charset=' . $this->charset;
// Options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
);
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$this->dbh->exec("SET NAMES utf8;");
}
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
...
May be I miss something ?
Thanks for help.
****EDIT****
Just after writing this message, I wonder if it does not come from escape(nomf.value) in the call of PHP asynchronous php code... I remove 'escape' and that works !!!
return checkFamilleAjax('code.php?idf='+idf.value
+'&nomf='+nomf.value
+'&mode=insert');
Javascript 'escape' change characters (accuentuated for example) to hexadecimal value : (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape * change * from french to english reference)
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"
This function is obsolete and 'encodeURI' ou 'encodeURIComponent' should be use when necessary.
Building a messaging system for my site and i have been stuck for days. I have this PHP link
<a href='user_msg.php?hash=$hash'>$name</a>
When you click on the link, it takes you to a page where you can send message to a user you've connected to (this connection is binded by the $hash)
in the page for sending the message, i hid the $hash in and hidden input value="$hash" and it sends the message to row in database with the $hash with the following scripts (They have no issue and work fine)
var msg_area = $('.msg_area');
msg_area.scrollTop(msg_area.prop("scrollHeight"));
$('#send_rep').submit(function (e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');
var posting = $.post(url, {rep_msg: $('#rep_msg').val(), hash: $('#hash').val()});
posting.done(function (data) {
alert('success');
});
});
PHP script to send
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['rep_msg']) && !empty($_POST['rep_msg']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_GET['hash'];
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['rep_msg'];
$hash = $_POST['hash'];
$rsql = <<<EOF
INSERT INTO messager (message, group_hash, from_id) VALUES('$rep_msg', '$hash', '$my_id');
EOF;
$rret = $db->exec($rsql);
$ursql = <<<EOF
SELECT * FROM User WHERE ID = '$my_id';
EOF;
$urret = $db->query($ursql);
while ($urrow = $urret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urrow['fname'];
$from_img = $urrow['image'];
header('Location: user_msg.php?hash=' . $hash);
}
}
The above Ajax Request and php script work fone to sedn the messages to database.
The issue not is getting the messages from database
This is the script i am currently using (not working)
PHP script to get message
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_GET['hash']) && !empty($_GET['hash']))
{
$hash = (int)$_GET['hash'];
$us_id = $_SESSION['log_id'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hash';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM User WHERE ID = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['image'];
if ($from_id != $_SESSION['log_id']) {
echo "
<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><div class='from_txt'><p>$messages</p></div></div>";
} else {
echo "
<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><div class='rep_txt'><p>$messages</p></div></div>";
}
}
echo "<input style='display: none' type='text' class='hash' name='hash' value='$hash' id='hash'>";
}
}
Ajax Request
setInterval(function() {
$('.msg_area').load("get_msg.php");
}, 2000);
But the get is not working. I suspect fro some reason, its not getting the $hash. Please is there a solution to this or am i trying something impossible.
Any help would be appreciated. If more info is needed please ask. Thanks in advance
Maybe $hash = (int)$_GET['hash']; would be $hash = (int)$_POST['hash'];
And you have more than just one $_GET...
In your ajax request you are using POST so you will need to get the hash with the POST as well: if (isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_POST['hash'];
Using '' in PHP indicates the actual string you are writing.
If you want to use a PHP variable in a string you should use "", so try changing $name
Check this for more info:
http://php.net/manual/en/language.types.string.php
Then, how do you hide your hash in the input?
You could use <input value="$_GET['hash']" ... />
In the script to send , does it enter the if? Try adding statements to see if SQL returns any error.
Hope this helps.
Answer to the question was to create a PHP SESSION for the $hash($_SESSION['hash'] = $hash) and to use this session all over the site with session_start().
I need to insert a value got from a document.getElementById into a sql query.
I need to do this because i'm trying to autofill a second input box depending on the result of the first (i.e. if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
Here is the code:
<?php
echo (" <form NAME='Form1' id='Form1' method=post class=statsform action=page.php > " );
echo (" <input type=text name=city id=city size=50 class=formfield value='$city' onBlur='Assigncode();' > " );
echo (" <input type=text name='Country' id='Country' size=12 value='$Country' > " );
?>
<script>
function Assigncode() {
var elemento = document.getElementById("city");
var elementoCod = document.getElementById("Country");
if (elemento != null && elemento.value != '') {
var city = elemento.value;
if (elementoCod == null || elementoCod.value == '') {
<?php
$query2 = "SELECT * FROM table WHERE city = 'put here the getElementById of the city' ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
$country = mysql_result($result2,0,"T_Country");
?>
eval( "document.Form1. Country").value = '<?php echo($country)?>';
}
}
}
</script>
Any suggestion?
Thanks
Here is a slightly modified version of an AJAX example script found on Wikipedia. It should give you the basic idea on how to proceed. If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
send-ajax-data.php:
<?php
$city = $_GET['city'];
$query2 = "SELECT * FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country = mysql_result($result2,0,"T_Country");
echo $country;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query.
Page1 has an input form. I validate the input field with a JavaScript:
<input type="text" name="frmBrand" size="50" onkeyup="BrandCheck();" maxlength="100" id="frmBrand" />
<span id="frmBrand_Status">Enter existing or new brand</span>
In the JavaScript I then call a PHP script:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
if (jsBrandName !==null || jsBrandName !== "")
{
document.getElementById("frmBrand_Status").textContent = jsBrandName
// alert(jsBrandName);
var xmlhttp = new XMLHttpRequest();
var url = "CheckBrand.php";
var vars = "jsBrandName="+jsBrandName;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var return_data = xmlhttp.responseText;
document.getElementById("frmBrand_Status").innerHTML = return_data;
}
}
xmlhttp.send(vars);
document.getElementById("frmBrand_Status").innerHTML = "processing.....";
}
}
So far so good. I do get results from the CheckBrand.php because it changes the frmBrand_Status. But I can't get any database results from the PHP page.
<?php
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
}
//by now we have connection to the database
else
{
if(isset($_POST['jsBrandName']))
{ //if we get the name succesfully
$jsBrandName = $_POST['jsBrandName'];
$dbBrandName = mysql_real_escape_string($jsBrandName);
if (!empty($dbBrandName))
{
$dbBrandName = $dbBrandName . "%";
$sqlQuery = "SELECT `BrandName` FROM `Brand` WHERE `BrandName` like '$dbBrandName' ORDER BY `BrandName`";
$result = mysqli_query($con, $sqlQuery);
$NumRows = mysqli_num_rows($result);
// $BrandName_result = mysql_fetch_row($BrandName_query);
echo "Result " . $dbBrandName . " ----- ". $jsBrandName . "Number rows " .$NumRows. " BrandName = " .$result. " SQL " .$sqlQuery;
if( $BrandName_result = mysql_fetch_row($BrandName_query))
{
While ($BrandName_result = mysql_fetch_row($BrandName_query))
{
echo "Brand = " .$BrandName_result[0];
}
}
}
else
{
echo "dbBrandName = empty" . $dbBrandName;
}
}
}
?>
When doing this, the html page shows the constant change of the normal variables. For example when the input field holds "Clu" I get the following output the span ID frmBrand_Status:
Result Clu% ----- CluNumber rows BrandName = SQL SELECT `BrandName` FROM `Brand` WHERE `BrandName` like 'Clu%' ORDER BY `BrandName`
Which looks good as the brandname gets the % appended, but the Number of rows is not shown (empty field?), the SQL Query is shown and looks good, but I don't get any results.
And the if( $BrandName_result = mysql_fetch_row($BrandName_query)) section will not be reached, so there definitely is something going wrong in calling the query.
When I run that same query through PHPMyAdmin, i do get the result I expect, which is 1 row with a brandname.
I'm using firebug to try and troubleshoot the SQL Query, but I can't find where I can check this and I probably can't since PHP is serverside. correct? But how should I then trouble shoot this?
Found what was wrong.
The $con string I was using to open the database was no longer available. On other pages in the site, the $con is available, I load the database using an include script on my index page. But it seems that the variable gets lost when it is called through the XMLHttpRequest(). Which is logical now I think of it, since this can also be a call to a remote server. So my CheckBrand.php page was just missing the $con var to connect to the database.
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax