ajax将php变量插入数据库

时间:2017-12-23 05:06:00

标签: javascript php jquery mysql ajax

我正在开展学生出勤标记工作。我想为此目的使用AJAX,但无法将数据插入数据库。以下是我的代码: -

HTML:

<a id="Present" href="#" class="btn btn-md btn-success" onClick="Present(<?php echo $id_1; ?>);">Present</a><br/><br/>

使用Javascript:

<script>
function Present(Pid){
    var Pyear = <?php echo $selected_year; ?>;
    var Pmonth = "<?php echo $selected_month; ?>";
    var Pday = <?php echo $selected_day; ?>;
    var Pdate = "<?php echo $selected_date; ?>";
    $.ajax({
        type: "POST",
        url: 'mark_present.php',
        data: { id : Pid, year : Pyear, month : Pmonth, day : Pday, date : Pdate },
        dataType: "JSON",
        success: function(data){
            $("#message").html(data);
            window.location.href = 'mark_attendance.php';
            //window.location.reload();
        },
        error: function() {
            alert("Failure");
        }
    });
}

mark_present.php:

<?php 
include "db.php";
    $student_id = $_POST['id'];
    $year = $_POST['year'];
    $month = $_POST['month'];
    $day = $_POST['day'];
    $date = $_POST['date'];

    $sql = "INSERT INTO `student_attendance` SET student_id = '$student_id', year = '$year', month = '$month', day = '$day', date = '$date', status = '1' ";
    $result = mysql_query($sql);

    if($result){
        return json_encode(array("message"=>true));
        //echo "success";
    }else{
        return json_encode(array("message"=>false));
        //echo "error";
    }
?>

2 个答案:

答案 0 :(得分:-1)

4.0
3.9924071330572093
3.982224060033384
3.9612544376696253
3.8080585081381275
0.03457371559793447
0.013026386180392412
0.006090856009723169
0.0018388671161891966
7.99632901621898
7.987892035846782
7.974282237149798
7.93316335979413
4.106158894193932
4.019755500146331
4.008967674404233
4.003810901304664

错误在您的插入查询上。

答案 1 :(得分:-1)

var Pyear = "<?php echo $selected_year; ?>";
var Pmonth = "<?php echo $selected_month; ?>";
var Pday = "<?php echo $selected_day; ?>";
var Pdate = "<?php echo $selected_date; ?>";

您需要使用"将php变量设为javascript检查this链接

将您的PHP代码更改为

<?php 
include "db.php";
$student_id = $_POST['id'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$date = $_POST['date'];

$sql = "INSERT INTO `student_attendance` SET student_id = '$student_id', year = '$year', month = '$month', day = '$day', date = '$date', status = '1' ";
$result = mysql_query($sql);
if(!$result){
    return json_encode(array("message"=>"There is some error".mysql_error());
} else {
    return json_encode(array("message"=>"Record inserted successfully"));
}
?>

将您的成功功能更改为

.success : function (data){
    console.log(data);
 }
.error : function(data){
    console.log(data);
 }

您将在控制台或成功消息中收到错误