简体   繁体   中英

Passing JavaScript variable to PHP through AJAX

I am following the guide from http://www.w3schools.com/php/php_ajax_database.asp , and I get the basic concept of how this works.

My code:

PHP:

<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select class="navbar-inverse" placeholder="PM Name" name="PMName"onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?>
</select>
<div id="txtHint"><b></b></div>

JavaScript:

<script>
    function showUser(str) {
      if (str !==".PM") {
        alert(str);
        if (str=="") {
          document.getElementById("txtHint").innerHTML="";
          return;
        } 
        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
          if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
          }
        }
      }
      xmlhttp.open("GET","getuser.php?q="+str,true);
      xmlhttp.send();
    }
</script>

and the getuser.php page:

<?php
$q = intval($_GET['q']);
include('./db.php');
$sqlPM= "SELECT * FROM report WHERE PMName = '".$q."'";
$result     = mysqli_query($con, $sqlPM);
?>

<table>
<?php
echo $q ;
?>
</table>

I have read through about 12 posts here and tried to make sense of the fact that most of these use some form of $.post('getuser.php' to send the variable over to the new PHP page, but the example from w3schools does not do this. On the initial page, my dropdown is populating fine from my database, and the value I select is being passed into the JavaScript function. I check this with alert(str); , but from there, it doesn't ever seem to get to the second PHP page. I tried testing that it came over using echo $q ; , but that comes up as empty.

What am I doing wrong that is causing the variable that the JavaScript function captures to not be passed over to the second PHP page?

From what I can see, I am following the instructions on the tutorial just fine.

$.post('getuser.php'此语法是jQuery JavaScript库所独有的。此外, $q不是integer ,考虑到最初执行的数据库查询,它是一个string ,所以为什么要包装$_GET['q']intval()吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM