Search code examples
phpmysqlajaxlivesearch

Livesearch php and ajax


I'm having some troubles with my code, I want it to execute the php file whenever I enter something but it isn't working

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    function getStates(value) {
        $.post("search.php", {name:value},function(data)
            $("#results").html(data);
        }); 
    }
</script>
</head>
<input type="text" onkeyup="getStates(this.value)"/>
<br>
<div id="results"></div>
<body>
</body>
</html>

php

<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST["name"];

$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
    echo "<div>" . $players["firstname"] . "</div>";
}

?>


Solution

  • From what I can see,you should change this

      '%search%' 
    

    to

      '%{$search}%'
    

    in

      $players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
    

    EDIT

    @user3187651 Assuming you've done everything right on the server side. Change your javascript to:

    function getStates(value) {
        $.post("search.php", {name:value},function(data){
            $("#results").html(data);
        }
        ); 
    }
    

    This should get rid of the error in the client side.