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!

1
  • I know nothing about PHP but $word = $_GET['word']; and $.post( doesn't look right Commented Mar 15, 2016 at 3:13

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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
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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.