Я делаю онлайн-приложение сканера штрих-кода и имею некоторые проблемы с отправкой javascript-переменной в php для моего запроса и возвращением его в свой html файл с данными.
Пользователь сканирует штрих-код (studentNr) studentnr → переменная, которая будет отправлена в файл php. в php файле: запрос для сравнения с переменным результатом запроса → обратно к параметру результата функции (данных). Звучит просто, но как мне это сделать правильно?
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>
И в моем файле testdb.php это выглядит так:
<?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);
}
}
Проблема в том, что я не могу получить данные из моего html файла в мой php файл, а также не знаю, как я могу вернуть полученные данные в свой html файл. в php файле. Как мне записать его обратно в html? Нужно ли использовать Ajax, JQuery,.. Любые другие решения?
Спасибо, что помогли мне!
добавляя это между скобками if (db_found), я получаю Внутреннюю ошибку сервера 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"]);
На вашем javascript вы отправляете параметр studnr
:
$.post('testdb.php', {'studnr' :studentenNr}, function(data){
В вашем php-скрипте вы пытаетесь получить значение из параметра studentenNr
:
$studnr = htmlspecialchars($_POST['studentenNr']);
Вам нужно закрепить свой сценарий
$studnr = htmlspecialchars($_POST['studnr']);
Редактировать:
Из-за этой строки вы получаете внутреннюю ошибку:
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
Вам нужно подготовить инструкцию SQL с параметрами, а затем связать их, поэтому строка должна быть (что-то вроде):
$sql = $db->prepare("select * from student where studentenNr= :studnr");
$sql->execute(array(':studnr' => $studnr ));