I can read Qrcode and what i want is to check if the text in qrcode is in remote database. I have a php file where I do some process to check if database is in mysql. But it does not work. below my code
/*part of js file
scan: function() {
console.log('scanning');
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result) {
var rs= result;
$.ajax({
type: 'POST',
data: rs,
url: 'http://url/page.php',
success: function(data){
console.log(data);
document.getElementById("info").innerHTML = data;
},
error: function(){
console.log(data);
alert('error');
}
});
return false;
}, function (error) {
console.log("Scanning failed: ", error);
} );
}
/* My php file
<?php
// Create connection
$conn = mysql_connect($servername, $username, $password);
mysql_select_db("database", $conn);
$result=$_POST['result'] ; //value from qrcode scanned by device
$sql="SELECT * FROM tabe WHERE code = '$result' ";
$rs = mysql_query($sql,$conn);
$count=mysql_num_rows($rs);
if($count == 1) {
echo "ok";
}
else
{
return "No Ok";
}
?>
Related
I am using jQuery for validation for simple form which has two selects
1- months (listing the month names and the value is month number)
2- years (from 2016-2022)
I want to check from the selected month and year whether there is a record on the database,
Mysql table has seperate month and year column.
For example:
How can I check January 2016 is already in the database using remote check?
remote.php is
$inspection_month = $_POST['sm'];
$inspection_year = $_POST['sy'];
$check_for_the_report = $db->single("SELECT id FROM dg_inspection_forms WHERE inspection_month = :sm AND inspection_year = :sy ",array("sm"=>"$inspection_month","sy"=>"$inspection_year"));
if($check_for_the_report){
echo "false";
} else {
echo "true";
}
The form validation part:
$('.btn-new-inspection-report-save').on('click', function(e){
e.preventDefault();
$("#newInspectionReportFormStep1").validate({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
if($('#newInspectionReportFormStep1').valid()) {
//Check if there is already a report for the selected Month and Year for that clinic
var sm = $('.new_inspection_month').find(':selected').data('fid');
var sy = $('.new_inspection_year').find(':selected').data('yid');
var flag = true;
$.ajax({
type: "POST",
url: '/apps/reports/check-for-previous-reports.php',
data: {sm:sm,sy:sy},
success: function(data) {
if (data === 'false') {
bootbox.alert("There is record for the selected month and year");
flag = false;
}
}
});
if(flag === false){
return flag;
e.preventDefault();
} else {
$('.loading').show();
$.ajax({
type: "POST",
url: '/apps/reports/new-inspection-report-step1-save.php',
data: $("#newInspectionReportFormStep1").serialize(),
success: function(data) {
$('#generateNewInspectionReportStep1').modal('hide');
var appModal = $('#generateNewInspectionReportStep2').modal('show');
appModal.load("/apps/reports/new-inspection-report-step2.php?report_id="+data+"");
$('.loading').hide();
}
});
}
}
});
You need separate php file that process database for you
Ajax php file should look something like this:
<?php
if(isset($_POST['month'])){
//Connect to database
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$result = mysqli_query($link, "SELECT * FROM table_name WHERE Month=".$_POST['month']." AND Year=".$_POST['year']);
$row_count = mysqli_num_rows($result);
}
$arr = array();
$arr['row_count'] = $row_count;
echo json_encode($arr);
exit;
And Jquery function:
function check_form(){
var monthx = $("#id_of_month_input").val();
var yearx = $("#id_of_year_input").val();
$.ajax({
type: "POST",
url: "url_to_your_ajax.php",
data: { month: monthx, year: yearx},
cache: false,
success: function(data){
var arr = $.parseJSON(data);
var row_count = arr['row_count'];
}
});
}
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
I'm using PhoneGap to create a Android QR code scanning app which act as a client, while the server is using PHP with MySQL (WAMP). Below is the section of QR scanning app to send the scanned result to the server, it manage to send and get reply from server, so I think the problem is at my server code in the next section
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: {
QR: result.text
},
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
Server code: to receive the QR scanned result as input then use the input to retrieve record from MySQL database to display the result on PHP page immediately, although my code can successfully retrieve the record from db, but the ECHO is show on my Android APP and not my server PHP interface.
I want to achieve result like Library Barcode Scanning result, is my method wrong?
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
You did couple of mistakes over here.
Please replace your code with below code:
$.ajax({
url : "http://192.168.1.2/receiveQR.php",
dataType: "json"
type : 'POST',
data : { QR : result.text},
success : function(response){
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response.data + '<br/>');
},
error : function() {
alert('Not working!');
}
});
<?php
if(isset($_POST['QR']))
{
//check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$reply=array();
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
$reply['data'] = "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply['message'] = "Server Received";
print json_encode($reply);
}
?>
use this one
javascript
formData = {
QR: result.text
}
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: formData,
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
php
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
I am getting the internal server error 500 on my ajax call. I am using a LAMP stack as my server and I've checked the permissions so that can't be my error.
Here's my javascript code:
//$('#addAthleteForm').trigger("reset");
//$(document).ready(function() {
$(function () {
$("#dialog").dialog({
autoOpen: false,
maxWidth: 600,
maxHeight: 500,
width: 500,
height: 460,
close: function () {
$('#addAthleteForm').trigger("reset");
}
});
$("#addAthlete").on("click", function () {
$("#dialog").dialog("open");
});
$("#addAthleteForm").submit(function (e) {
e.preventDefault();
var postData = jQuery(this).serialize();
$("#dialog").dialog("close")
$.ajax({
type: "POST",
url: "AddAthletes.php",
dataType: 'json',
data: postData,
success: function (data) {
alert(data);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
$("#editAthlete").submit(function (e) {
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "GetAthlete.php",
dataType: 'json',
data: editData,
success: function (data) {
var form = document.forms['addAthleteForm'];
form.fname.value = data.fname;
form.lname.value = data.lname;
form.school.value = data.school;
form.agegrp.value = data.agegrp;
}
});
$("#dialog").dialog("open");
});
})
and here's my php code:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$school = $_POST['school'];
$agegrp = $_POST['agegrp'];
$db = mysqli_connect("localhost", "root", "passwrd","site");
if(!$db){
exit("Error in database connection");
}
else{
$result = mysqli_query($db, "SELECT * FROM `School` WHERE `SchoolLong`='$school'");
$row = mysqli_fetch_array($result));
$SchoolID = $row['SchoolID'];
$result = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegrp'");
$row = mysqli_fetch_array($result));
$AgeGroupID = $row['AgeGroupID'];
mysqli_query($db, "INSERT INTO `Athlete` (`NameFirst`,`NameLast`, `SchoolID`, `AgeGroupID`) VALUES ('$fname', '$lname', $schoolID, $agegrpID)");
}
echo json_encode($fname);
?>
I'm not to sure where this error is coming from. The code used to work.
Syntax error in below line:-
$row = mysqli_fetch_array($result));
It should be :-
$row = mysqli_fetch_array($result);
same mistake for below mysqli_fetch_array()
Your corrected block of code are:-
$result = mysqli_query($db, "SELECT * FROM `School` WHERE `SchoolLong`='$school'");
$row = mysqli_fetch_array($result);
$SchoolID = $row['SchoolID'];
$result = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegrp'");
$row = mysqli_fetch_array($result);
$AgeGroupID = $row['AgeGroupID'];
I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request