从Ajax传递数据到PHP

时间:2015-06-29 08:06:13

标签: php ajax

我在ajax中有以下代码。我将两个参数$job_idq传递给名为interview.php的页面,但是。但是,该页面向我发出警告,$job_id未定义。我不知道如何使用AJAX POST或GET多一个变量。

我的ajax文件是:

<script>
function showSuccess ($getid,str) {
  var job_id= $getid;
var resp;
 if (window.XMLHttpRequest) {
    resp = new XMLHttpRequest();
    xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { 
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "job_id="+job_id
     xmlhttp.open("POST", 
      "interview.php?q="+str); 
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
     xmlhttp.send(data);
   xmlhttp.onreadystatechange =
  function display_data() {
   if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

}
     } else {
        alert('Request not successful.');
      }
     }
  }


</script>

interview.php:

<?php 
$q = intval($_POST['q']);
?>
<?php 

$getid = $_POST['job_id'];?>

<?php
include('includes/conn.php');

$row="SELECT  idNo,id,name,jobTitle,SUM(points) AS total FROM shortlist WHERE job='$getid' GROUP BY id ORDER BY total DESC LIMIT $q";
$query=mysqli_query($conn,$row) or die(mysqli_error($conn));

while($row=mysqli_fetch_array($query))
{
  echo $row['name'];
}

mysqli_close($conn);
?>

2 个答案:

答案 0 :(得分:0)

如果您不理解javascript和ajax,只需尝试使用像jQuery这样简单的东西。

你实际上只给PHP脚本一个变量,这就是你得到这个错误的原因。试着改变这个:

xmlhttp.open("POST", "interview.php?q="+str);

xmlhttp.open("POST", "interview.php?q="+str+"&job_id="+job_id);

答案 1 :(得分:0)

将您的data更改为此var data = "job_id="+job_id+"&q"+str Undefined index: q是因为您使用post方法获取数据,并且您使用get方法发送数据,这就是您收到错误的原因。 尝试以下代码。

xmlhttp.open("POST","interview.php"); 
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
xmlhttp.send(data);