tags:

views:

28

answers:

1

The jquery function that I'm using is:

$.getJSON("rpc2.php?queryString=" +inputString+"", function(data) { 
if(data.length >0) {
$.each(data, function(i, data){
var city= data.city;
var country= data.country;
$('#suggestions').show();
$('#autoSuggestionsList').html('<li>'+ city+'</li>');
 });
 }
 });

The PHP looks like:

if(strlen($queryString) >0) {
$query = "SELECT * FROM cities WHERE city_accented LIKE '$queryString%' LIMIT 5";
$result = mysql_query($query) or die("There is an error in database");
$json = array();
while($row = mysql_fetch_array($result)){
$json['city'] = $row['city_accented'];
$json['country'] = $row['country'];
$data[] = $json;  
}
}
print json_encode($data);

The response that I'm getting from PHP is:

[{"city":"Lors","country":"ad"},{"city":"Lo Serrat","country":"ad"},{"city":"Lobabi","country":"af"},{"city":"Lobya","country":"af"},{"city":"Locakan","country":"af"}]

The problem is that in autoSuggestionsList DIV only the first city is listed, not all five from PHP response. Why there is no other cities from php response in autoSuggestionsList div?

+3  A: 

Try:

$('#autoSuggestionsList').append('<li/>' + city + '</li>');
sje397
@sje397 - I tried with append but in that case the list won't stop when it reaches the number of 10 cities. Every new city from PHP response is added to the div.
Sergio
@Sergio - that's a different problem, but pretty easy to solve. When you're adding cities, you have the index variable (`i`) available - so just put `if(i < 10)` before the line I wrote above.
sje397
Oh, and you might want to call `.empty` on the div before adding anything if you are doing multiple ajax requests.
sje397
@sje397 - Nope, it didn't work. I just tried that. When I add append('<li/>'+ i + city + '</li>') just to see the value of index I never get index value higher of 4.Something like:0La Cortinada,1La Costa,2L'Aldosa,3L'Aldosa,4La Maana,0Lors,1Lo Serrat,2Lobabi,3Lobya,4Locakan,....
Sergio
@sje397 - when I try with if(i < 4){$('#autoSuggestionsList').empty().append('<li>'+ city +'<li>');} I'm still getting only the first cityt in PHP response list.
Sergio
If you call empty before each append, you will clear the div each time, and only have one item in it.
sje397
An array can't have multiple items at index 0 - something else must be going wrong. Check the data with firebug.
sje397
@sje397 - Thanks. I found the solution. If I put .empty() before $.each only the last four listed cities will appear in the div. Thanks again.
Sergio