我創建了一個使用jQuery(ajax)發送數據到php的基本表單。 PHP應該將基於數據的新記錄插入到mysql數據庫中。原因是因爲我想插入數據庫,而不必提交整個表單,然後使用提交操作獲取其他內容。看起來jquery工作正常,因爲alert()顯示變量的正確輸出,但PHP不插入數據,我也沒有收到錯誤。我不明白爲什麼這不起作用?我認爲這是我的$ post()的問題,因爲下面的函數沒有執行,但我無法找出錯誤。任何幫助調試這將非常感激。或者,如果有人知道另一種獲得相同功能的方式,那也會很棒?謝謝。 (下面的代碼現在工作得很好。我想通了,這是一個類型轉換的錯誤,我固定它。希望有人能找到這個有用!)Ajax和jquery沒有正確地發送數據到php
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
你可以看看這裏:http://stackoverflow.com/questions/12686457/sending-values-of-a-form -with-ajax-via-post/12686509#12686509與jQuery ajax – zer02
順便說一下,請確保清理通過POST獲得的數據。 – omnidan
我修好了。這實際上只是我的SQL中的一個語法錯誤,以及與我的一個數據庫列的類型差異錯誤。 $ grade變量作爲字符串傳入PHP。一旦我將所有變量都包含在intval()中,它就會按預期工作。長時間盯着代碼,有時你會失明。哈哈。 – natethenerd