使用javascript,mysql和php将记录插入数据库

时间:2015-04-22 19:43:14

标签: javascript php ajax mysqli

我有以下js函数,它产生一个ajax请求,但由于某种原因它没有这样做。我检查了警报网址并按原样显示它,因此声明了所有变量。

var request = new XMLHttpRequest();
var url = "ajax_js/q_ajax.php?q="+ques+
                            "&ans="+ans+
                            "&a="+inp[0].value+
                            "&b="+inp[2].value+
                            "&c="+inp[4].value+
                            "&d="+inp[6].value+
                            "&cor="+checked+
                            "&def="+input+
                            "&q_n="+q_name+
                            "&c_id="+c_id;
request.onreadystatechange=function (){
    if(request.readyState==4 && request.status==200){
        alert(request.responseText);
    }
    request.open("GET", url, true);
    request.send();
}

以下是php文件中的代码。

<?php
require("db_conx.php");
$q = $_GET['q'];
$ans = $_GET['ans'];
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$cor = $_GET['cor'];
$def = $_GET['def'];
$q_n = $_GET['q_n'];
$c_id = $_GET['c_id'];


$q = mysqli_escape_string($con, $q);
$ans = mysqli_escape_string($con, $ans);
$a = mysqli_escape_string($con, $a);
$b = mysqli_escape_string($con, $b);
$c = mysqli_escape_string($con, $c);
$d = mysqli_escape_string($con, $d);
$cor = mysqli_escape_string($con, $cor);
$def = mysqli_escape_string($con, $def);
$q_n = mysqli_escape_string($con, $q_n);
$c_id = mysqli_escape_string($con, $c_id);


/* Modify id for the system  */
$query = mysqli_query($con, "INSERT INTO course_quiz (course_id, quiz_name, question, des_answer, ChoiceA,
                                                      ChoiceB, ChoiceC, ChoiceD, correct, def)
                            VALUES ('$c_id', '$q_n', '$q', '$ans', '$a', '$b', '$c', '$d', '$cor', '$def')");
echo('Question has been saved');
/* header('Location: ../instr_home.php'); */

我在同一页面上还有另一个ajax调用(工作完美),我认为问题的原因。 XMLHttpRequest的变量也被命名为不同。

提前谢谢你!

1 个答案:

答案 0 :(得分:0)

使用此更改代码,您会发现错误

request.onreadystatechange=function (){
    //if(request.readyState==4 && request.status==200){
        alert(request.responseText);
    //}
}
request.open("GET", url, false);
request.send();