I have a project with barcodescanner library for phonegap. i have success scan QR Code image with this. And i want to authenticate the code inside QR Code with my database. How to do it?
i have barcodescanner.js:
document.addEventListener("deviceready", init, false);
function init() {
}
function scan() {
log("scanning");
cordova.plugins.barcodeScanner.scan(scanSuccessCallback, scanErrorCallback);
}
function scanSuccessCallback(result) {
log(JSON.stringify(result));
konfirmasi();
/*
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
*/
}
function scanErrorCallback(error) {
alert("Scanning failed: " + JSON.stringify(error));
}
function encode() {
log("encoding");
if (device.platform == "Android") { //Not supported on iOS
var stringToEncode = "http://www.sap.com";
cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, stringToEncode, encodeSuccessCallback, encodeErrorCallback);
}
else {
log("Encoding is not supported on iOS. See https://github.com/wildabeast/BarcodeScanner/issues/106");
}
}
function encodeSuccessCallback(result) {
log(JSON.stringify(result));
}
function encodeErrorCallback(error) {
alert("Encoding failed: " + JSON.stringify(error));
}
function log(line) {
var results = document.getElementById("scan_results");
//results.innerHTML+= "<br>" + line;
}
And this is my authentition php:
<?php
header("access-control-allow-origin: *") ;
include "connect.php";
$kode_konfirmasi = $_POST['konfirmasi'];
$kurir = $_POST['kurir'];
$miss = 'miss';
$delivered = 'delivered';
$query_kode = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Belum Terkirim'";
$res_kode_ok = mysqli_query($dbc, $query_kode);
$query_exp = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Terkirim'";
$res_kode_expired = mysqli_query($dbc, $query_exp);
$query_ok = "SELECT pengiriman.kode_transaksi, pengiriman.status FROM pengiriman, kurir WHERE pengiriman.id_kurir = kurir.id_kurir AND kurir.username = '$kurir' AND pengiriman.kode_transaksi = '$kode_konfirmasi'";
$res_kurir = mysqli_query($dbc, $query_ok);
if(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)>0){
$res_upd = mysqli_query($dbc, $query_upd);
$output = array('status' => true);
echo json_encode($output);
$query_upd = "UPDATE pengiriman SET status = 'Terkirim' WHERE kode_transaksi = '$kode_konfirmasi'";
}elseif(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)==0){
$output = array('status' => $miss);
echo json_encode($output);
}elseif (mysqli_num_rows($res_kode_expired)>0){
$output = array('status' => $delivered);
echo json_encode($output);
}else{
$output = array('status' => false);
echo json_encode($output);
}
?>
I have a script for authenticate the code inside QR Code manually by insert it in form html like this
$(document).on('pageinit','#manual',function(){
$(document).on('click','#submit',function(){
if($('#kode').val().length>0){
var un = window.localStorage.getItem('uname');
var kode = $('#kode').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/konfirmasi.php',
data:{ kurir : un,
konfirmasi : kode
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(hasil){
console.log(hasil);
if(hasil.status==true){
alert('Berhasil! Konfirmasi kode ' + kode + ' berhasil.')
$.mobile.changePage("#konfirmasi");
console.log('Konfirmasi Berhasil');
}else if(hasil.status=='delivered') {
alert('Error! Kode '+ kode + ' telah dikonfirmasi.');
}else if(hasil.status=='miss'){
alert('Error! Data kurir tidak sesuai.');
}else{
alert('Gagal, Kode konfirmasi tidak sesuai.');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
So, how i can authenticate the code from scanning result immediately when scan success?
Related
So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>
try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);
I tried to retrieve data from php but when I run the code it not passing in javascript. It gives an error. Can anyone help?
Javascript
function updateCountryFeatures() {
$.ajax({
url: "libs/php/getCountryBounds.php",
type: 'POST',
dataType: 'json',
data: {
iso3: countryAlpha2Code
},
success: function(result) {
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("updateCountryFeatures: " + errorThrown + " " + jqXHR + " " + textStatus);
}
});
}
PHP:
$executionStartTime = microtime(true);
$countryBorders = json_decode(file_get_contents("libs/php/countries/countries_large.geo.json"), true);
$border = null;
foreach ($countryBorders['features'] as $feature) {
if ($feature["properties"]["ISO_A3"] == $_REQUEST['iso3']) {
$border = $feature;
break;
}
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['executedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $border;
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
I'm currently working on a chat application which will support up to four windows simultaneously.
When I open a new chat-window, the scrollbar won't go down even though the function is called. Whenever I send a message it works fine.
function createChat(caller_id) {
$.ajax({
type: 'POST',
url: 'create_chat_interface.php',
data: {
caller_id: caller_id,
},
success: function(data) {
if (!$('#chat-history-' + caller_id).length) {
if ($.trim($("#chat1").html()) == '') {
$('#chat1').html(data);
document.getElementById("chat-close").id = 'chat-close1';
} else if ($.trim($("#chat2").html()) == '') {
$('#chat2').html(data);
document.getElementById("chat-close").id = 'chat-close2';
} else if ($.trim($("#chat3").html()) == '') {
$('#chat3').html(data);
document.getElementById("chat-close").id = 'chat-close3';
} else if ($.trim($("#chat4").html()) == '') {
$('#chat4').html(data);
document.getElementById("chat-close").id = 'chat-close4';
}
$('#chat-input-' + caller_id).focus();
scrollDown(caller_id);
}
}
})
}
function fetch_chat_history($caller_id, $db)
{
$query = "SELECT * FROM messages WHERE from_id = '$caller_id'
OR to_id = '$caller_id' ORDER BY timestamp ASC";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$output = '<ul>';
foreach ($result as $row) {
if ($row['from_id'] == $caller_id) {
$output .= '
<li class="received"><p>' . $row['message'] . '</p></li>';
} else {
$output .= '
<li class="sent"><p>' . $row['message'] . '</p></li>';
}
}
$output .= '</ul>';
return $output;
}
My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});
guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});