jQuery remote check validation - php

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'];
}
});
}

Related

problem with ajax url address .its not working

I want to compare my field value to mysql field with ajax.
this is my ajax cod:
$("#checkCodeButton").click(function() {
var enteredCodeField = $("#order-discount").val();
$.ajax({
type: 'post',
url: 'check.php',
data: {
enteredCode: enteredCodeField
},
dataType: "text",
success: function(data) {
alert(data);
}
})
});
and this is my code in check.php
<?php
$link = mysqli_connect("localhost", "root", "", "animating-wp");
date_default_timezone_set('Asia/Tehran');
$days = 0;
$hours = 0;
$discountPercent = 0;
if (isset($_POST['enteredCode']) && !empty($_POST['enteredCode'])) {
$SelectDiscountQuery = "SELECT * FROM discounts WHERE discount_code = ' " . $_POST['enteredCode'] . " ' ";
$discountResult = mysqli_query($link, $SelectDiscountQuery);
if(mysqli_num_rows($discountResult) > 0){
echo "blah blah";
} else {
echo "blah";
}
}
but I dont know why when I'm clicking on the button it doesn't work?
( also I run this in wordpress them and linked jquery in script>
thanks

Check Barcode valid from phonegab android to remote phpfile

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";
}
?>

insert in database using json jquery and php

i want to add data to my database by passing as a json string then using php what i have done but adds an empty line in the database instead of adding the data that i sent and i get the alert("fail") message where is the mistake please
here is my save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
and here is my php file insert.php
<?php
$json = isset($_POST['data']) ? $_POST['data'] : "";
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$new['email']."','".$new['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Can you try this:
JS:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
PHP Code:
<?php
$email = isset($_POST['email']) ? $_POST['email'] : "";
$mdp = isset($_POST['mdp']) ? $_POST['mdp'] : "";
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$email."','".$mdp."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Get data using this way in PHP
$data = json_decode(file_get_contents('php://input'));
$email = $data ->email;
$mdp = $data ->mdp;
In your PHP, each individual variable that you're passing through (i.e. email and mdp) is passed as individual $_POST data, not into a single $_POST variable called 'data'. Right after your opening PHP tag, check for the email and mdp:
$email = (isset($_POST['email']) ? $_POST['email'] : "");
$mdp = (isset($_POST['mdp']) ? $_POST['mdp'] : "");
$conn= ....
You can try this:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {'email': eml,'mdp': mp}; //json
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: data,//pass it here
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
php:
<?php
if(isset($_POST['email'],$_POST['mdp']) {
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$_POST['email']."','".$_POST['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
try like this,
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
// dataType: 'json',
data: {"data":JSON.stringify(data)},
// contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
Try this :
function save() {
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
type: 'POST',
url: "http://localhost:800/test/insert.php",
//dataType: 'json',
data: {"data": JSON.stringify(data)},
//contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == 'created')
alert('Success');
else
alert('Fail');
}
});
}

Json echoing empty data to AJAX

After both sql commands are run, JSON should send an updated result to the AJAX script. Upon triggering, a spot opens in the page where the data should be populating, but nothing there. The PHP below is not creating any error messages and the data is updating to the db. I wish I had a more specific type of question but Im not finding the cause of the problem.
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank from ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
if(is_null($avrank)){$avrank ="null";}
if(!$mysqli)
{
$arr = array ('status'=>'fail');
echo json_encode($arr);
}
else
{
echo json_encode($avrank);
}
exit;
}
}
AJAX
<script type ="text/javascript">
$('#products .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
url: '../rate.php',
data: { storyidr: storyidr, value: value },
type: 'POST',
success: function (data) {
$('#response').append('<li>' + data + '</li>');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
html
<ul id="response">
</ul>

jQuery and MySQL

I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)

Categories