0

I have a table: DB

 city
 -------
 cityID
 cityname
 store

I have then a form HTML:

<input type="text" class="store">

GOAL:

I would like javascript, after I enter the store, (if the entered value is already in the DB) displays an alert like:

"Store is already entered for the following cities: New York (ID#), Boston(ID#), Springfield(ID#)"

I've tried with a Json file:

<?php include ('connectionlink.php');
 $word = $_GET['word'];

$search = "SELECT
            store as value,
            cityID,
            cityname,
            FROM city
            WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
    $row['value']=htmlentities(stripslashes($row['value']));
    $row['cityID']=$row['cityID'];  
    $row['cityname']=$row['cityname'];      
    $row_set[] = $row;
}
echo json_encode($row_set);
?>

And javascript

$(document).ready(function (){

 $('.store').on('change', function(){
    var storeValue = $('.store').val();

    $.post('stores.php',{'word' : storeValue}, function(data) {
          alert("Data: " + data);
    }); 

 });
});

I feel I'm almost there, because after typing the store I get an alert of Undefined index word error and then the alert displays all the data in my table with the Json format. It's like if it doesn't search just for my word, but just returns everything. Thanks for your help!

mmativ
  • 1,414
  • 14
  • 25
codeispoetry
  • 373
  • 2
  • 13

2 Answers2

2

You are doing a post request, so read the parameter with $_POST

$word = $_POST['word']

Also make sure that you handle sql injection How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • P Thanks Arun, it worked. Could you help me to display in the alert not the row json, but a little bit mor friendly user. Now I get `[{"value"."storename"."cityId"...` a bit hard to read! Thanks – codeispoetry Mar 15 '16 at 04:13
1
<?php include ('connectionlink.php');
//as you are doing a post request...
 $word = $_POST['word'];

$search = "SELECT
            store as value,
            cityID,
            cityname,
            FROM city
            WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
    $row['value']=htmlentities(stripslashes($row['value']));
    $row['cityID']=$row['cityID'];  
    $row['cityname']=$row['cityname'];      
    $row_set[] = $row;
}
echo json_encode($row_set);
?>
Ece
  • 148
  • 9