我正在使用jQuery验证简单表单,它有两个选择
1个月(列出月份名称,值为月份号)
2年(2016-2022)
我想从选定的月份和年份检查数据库中是否有记录, Mysql表有单独的月份和年份列。
例如:
如何使用远程检查检查2016年1月数据库中是否已存在?
remote.php是
$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";
}
表单验证部分:
$('.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();
}
});
}
}
});
答案 0 :(得分:0)
您需要单独的php文件来处理数据库
Ajax php文件看起来应该是这样的:
<?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;
和Jquery函数:
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'];
}
});
}