Simbolae Simbolae - 7 months ago 62
Ajax Question

ajax to insert php variables into database

I'm working on Student Attendance Marking. I want to use AJAX for this purpose but am not able to insert data into database. Following is my code:-

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

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

you need to use " to get php variable to javascript check this link

Change your PHP code to

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

And change your success function to

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

you will get the error in console or success message

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download