简体   繁体   中英

ajax, php and mysql connection issues

Am fetching data from database using ajax but it is failing. The data should be displayed at the div I have declared in the main page called 'display'. The query runs but nothing is printed on the div. Here are my codes:

//ajax:
<script>
function Jobs(str) {

    if (str == "") {
        document.getElementById("display").innerHTML = "";
        return;
    } else {
        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("display").innerHTML = xmlhttp.responseText;
            }
        }

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

        xmlhttp.send();
    }
}
</script>
//php
?php $q = intval($_GET['q']);?>

<?php

    include('includes/conn.php');
    $row="SELECT DISTINCT title,id FROM jobs  WHERE dept='$q' AND state=0 ORDER BY id";
    $query=mysqli_query($conn,$row) or die(mysqli_error($conn));
    while($row=mysqli_fetch_array($query))
    {
        echo $row['title'];
    }
    mysqli_close($conn);
    ?>

Sample ajax example codes

addfield.php file:

<html>
    <head>
    <script>
    function Jobs(str) {

        if (str == "") {
            document.getElementById("display").innerHTML = "";
            return;
        } else {
            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("display").innerHTML = xmlhttp.responseText;
                }
            }

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

            xmlhttp.send();
        }
    }
    </script>
    </head>
    <body>

    <p><b>Start typing a name in the input field below:</b></p>
    <form> 
    First name: <input type="text" onkeyup="Jobs(this.value)">
    </form>
    <p>Suggestions: <span id="display"></span></p>
    </body>
    </html>

search.php code:

<?php
echo $q = $_REQUEST["q"];

?>

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