Problem with jquery and mySql autocomplete

search.php

$text = $mysqli->$_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $text . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
    if (!$first) { $json .=  ','; } else { $first = false; }
    $json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;

index.php

1) HTML

<body>
Text: <input type="text" id="autocomplete" />
</body>

2) jQuery

    $( "#autocomplete" ).autocomplete({
        source: function(request, response) {
            $.ajax({ url: "http://localhost/testing/auto/search.php",
            data: { term: $("#autocomplete").val()},
            dataType: "json",
            type: "POST",
            success: function(data){
                response(data);
            }
        });
    },
    minLength: 2
    });

When I type 2 letters, it gives me all the names in my database, even if these two letters do not match any of the names.

How does this happen and how to fix it?

+3
source share
6 answers

It seems that my comment worked as an answer, hence this answer.

What does it do $mysqli->$_POST['term']? I think you should have it $text = $_POST['term'];. That should work.

+1
source

source , . request.term, $("#autocomplete").val(). term PHP, SQL :

SELECT name FROM males WHERE name LIKE '%%' ORDER BY name ASC

males. source :

source: function(request, response) { 
    $.ajax({
        url: "http://localhost/testing/auto/search.php",
        data: { term: request.term },
        dataType: "json", 
        type: "POST", 
        success: function(data) { 
            response(data);  
        }
    });
}   

jQuery-UI, , DOM , #autocomplete , .

, :

, , . :

  • A request , term, , . , " " , "" " ".
+1

PHP

$text = $_POST['term'];

$query = "SELECT name FROM males WHERE name LIKE '%" . $mysqli->real_escape_string($text) . "%' ORDER BY name ASC";
$result = $mysqli->query($query);

echo json_encode($result->fetch_all(MYSQLI_ASSOC));

, SQL. , @mu , .

+1

, search.php . $_GET ['term'] , .

LIKE '% text%' LIKE 'text%'.

Firebug , search.php AJAX. BTW, , jquery ?

0

, sql. U

$query = "SELECT name FROM males WHERE name LIKE '%$text%' ORDER BY name ASC"

,

Aaron Maartha ...

"AA", : Aaron, Maartha. . % text% , .

,

$query = "SELECT name FROM males WHERE name LIKE '$text%' ORDER BY name ASC"

"AA", : Aaron.

, jQuery , .

0

$_REQUEST['term'] $_POST['term'].

0

All Articles