johhny
johhny

Reputation: 1

PHP Ajax live search is only returning a single result

I am trying to create a simple live search where I can input a city name and it'll return all the relative cities.

This is my code. It works except for one thing. It's only returning a single city on input. Shouldn't it returning multiple cities if the the input word is partially matched with them? Can you tell me what I'm doing wrong?

// HTML

<form action="" method="POST">
 <input type="text" id="city-box" class="type-input" name="sel-city" autocomplete="off" value="<?php if(!empty($post_city)) { echo $post_city; }?>" placeholder="Type City Name" />

 <input type="hidden" id="city-box-id" name="sel-city-hidden" value="<?php if(!empty($post_city_hidden)) { echo $post_city_hidden; }?>"/>

 <div id="display-cities"></div>

 <input type="submit" name="search" value="Search" />
</form>

// JAVASCRIPT

<script>
$(document).ready(function() {

$('#display-cities').hide();

 $("#city-box").keyup(function() {
     var name = $('#city-box').val();
     if (name == "") {
       $('#display-cities').hide();
     } else {

       $.ajax({
           type: "POST",
           url: "snippets/backend-search.php",
           dataType: 'json',
           cache: false,
           data: { term: name },
           success: function(data) {
            var citydata  = '<div class="output-results"><p class="output-p1">' + data.cityname + '</p><p class="output-p2">' + data.provincename + ', '+ data.countryname + '</p></div>';
            var citydata2 = '' + data.cityname + ', ' + data.provincename + ', ' + data.countryname + '';

            $("#display-cities").html(citydata).show();

            $( ".output-results" ).click(function() {
              $("#city-box-id").val(data.cityid);
              $("#city-box").val(citydata2);
              $("#display-cities").html(citydata).hide();
            });

           }
       });
     }
 });
});
</script>

// BACKEND-SEARCH.PHP

if(isset($_POST["term"])){

 $param_term = $_POST["term"] .'%';

 $get_city_select = $db->prepare("SELECT cities.city_id, cities.city_name, 
 provinces.province_id, provinces.province_name, countries.country_id, countries.country_name 
 FROM cities
 LEFT JOIN provinces ON cities.province_id = provinces.province_id
 LEFT JOIN countries ON provinces.country_id = countries.country_id
 WHERE city_name LIKE :param");
 $get_city_select->bindParam(':param', $param_term);
 $get_city_select->execute();
 $result_city_select = $get_city_select->fetchAll(PDO::FETCH_ASSOC);
 if(count($result_city_select) > 0) {
  foreach($result_city_select as $row) {
   $s_city_id      = $row['city_id'];
   $s_city_name    = $row['city_name'];

   $s_province_id  = $row['province_id'];
   $s_province_name  = $row['province_name'];

   $s_country_id     = $row['country_id'];
   $s_country_name  = $row['country_name'];

   echo json_encode (array("cityid" => "{$s_city_id}", "cityname" => "{$s_city_name}", 
   "provincename" => "{$s_province_name}", "countryname" => "{$s_country_name}"));
  }
 }
}

Upvotes: -2

Views: 279

Answers (1)

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4774

You are calling json_encode each time you output a city result. This will result in multiple bits of JSON. Instead, put all the results in an array and encode that with json_encode.

EDIT:

You have now done:

$arr[] = array (
  "cityid"        => "{$s_city_id}",
  "cityname"      => "{$s_city_name}",
  "provincename"  => "{$s_province_name}",
  "countryname"   => "{$s_country_name}"
);

Here, you are building a new array for each city result. Instead, do this:

$cities = [];
foreach($result_city_select as $row) {
  $city = new \stdClass();
  $city->id = $row['city_id'];
   // ...more city properties...
  array_push($cities, $city);
}
echo json_encode($cities);

For each city, a new anonymous PHP object (stdClass) is created, and its properties are filled with city information. This object instance is then added to the cities array, which is finally sent to stdout as JSON.

Each city will have to be a JSON object, and not an array.

Upvotes: 1

Related Questions