简体   繁体   中英

Can someone spot my error (autocomplete text box)?

So far I have HTML:

<div id="box" style="width:400; height:400; margin-left:auto; margin-right:auto; margin-top:100;">
<h2>Enter a word</h2>
<input type="text" id="input" ></input>
</div>
<div id="suggest">
</div>

Javascript:

<script type ="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
var input = $("#input").val();
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: "input"+input,
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
});
});
</script>

PHP:

<?php

$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error()); 
mysql_select_db ("~") or ("Database not found");

$input = $_REQUEST['input'];

$input = mysql_real_escape_string(trim($input));

    $sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";

    $data = mysql_query($sql);

    $arrcnt = -1;

    $dataArray = array();

    while ($temp = mysql_fetch_assoc($data)) 
        {
            foreach($temp as $key=>$val) {
                $temp[$key] = stripslashes($val);
                $arrcnt++;
        }
        $dataarray[$arrcnt] = $temp;
    }

    $list = "<ul style='width:100;height:auto;'>";

    foreach($dataArray as $val) {
        $list .= "<li>".$val['DesiredColumnContainingDesiredData']."</li>";
    }

    $list .= "</ul>";

    echo $list;



?>

Now, these codes are supposed to work together to autocomplete the div with id="suggest" then populate the text field with id="input" when selected ... I keep getting alert that reads: <ul style='width:100;height:auto;'></ul>

change ajax code like this,

$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: {"input":input},
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});

The issue is because in php your variable name is different . You added $dataarray instead of $dataArray

Additionally for ajax

You can pass data as a string or as an object

data:{"input":input}

or

data:"input="+input

add type: 'POST' in ajax

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