簡體   English   中英

Ajax和jQuery無法將數據正確發送到php

[英]Ajax and jquery not sending data correctly to php

我創建了一個使用jquery(ajax)將數據發送到php的基本表單。 PHP應基於數據將新記錄插入mysql數據庫。 這樣做的原因是因為我想在不提交整個表單的情況下向數據庫中插入數據,然后稍后再使用Submit操作。 似乎jquery可以正常工作,因為alert()為變量顯示了正確的輸出,但是PHP沒有插入數據,並且沒有收到錯誤。 我不知道為什么這不起作用? 我認為$ post()有問題,因為下面的函數無法執行,但我無法查明錯誤。 任何調試它的幫助將不勝感激。 或者,如果有人知道獲得相同功能的另一種方法,那就太好了嗎? 謝謝。 (下面的代碼現在可以正常工作。我發現這是一個類型轉換錯誤,我已將其修復。希望有人可以找到這個有用的方法!)

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

您是否在HTML頁面中加入了這一行?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

再次出現一個例子,可能對您有幫助

<script>
$(document).ready(function(){
 $("input").keyup(function(){
   txt=$("input").val();
   $.post("my_page.asp",{suggest:txt},function(result){
     $("span").html(result);
  });
 });
});

但您的代碼似乎太正確了!

我建議通過將錯誤處理程序附加到$.post調用來繼續調試,您的代碼可能如下所示:

$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
    // success
}).fail(function(response) {
    // failure
});

此外,您應該檢查:

  • 腳本是否在服務器上運行? ajax可能不適用於file:///地址
  • 從javascript位置到php文件的路徑正確嗎?
  • 瀏覽器開發人員工具對已發起的請求怎么說?

我修好了它。 實際上,這只是我的SQL中的語法錯誤和數據庫列之一的類型差異錯誤。 $ grade變量作為字符串傳遞到PHP中。 一旦將所有變量包裝在intval()中,它就會按預期工作。 盯着代碼很長時間,有時您會視而不見。 哈哈。

感謝omnidan提供有關消毒的提示。 這是我曾經將其應用於應用程序的一個很好的指導:

http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM