0

I'm trying to populate array in my validation code with distinct values from one column, and logic was that on focus on certain element I would send ajax request and populate array with JSON response. But I'm still a novice in JQuery and it seems I cant get it right, so if anyone can help.

$('input#search').on("focus", function(){

        $.ajax({
                type:"get",
                dataType: "json",
                url:"ajax_php/get_distinct_cities.php",
                    success:function(data){
                        $.each( data.city, function( i, itemData ) {
                           cities[i] = itemData;
                        });
                    }
                 });

    });

PHP:

<?php

    mysql_connect("localhost","root","");
    mysql_select_db("pickante");

    $sql = "SELECT DISTINCT city FROM uc_items";

    $result = mysql_query($sql);

    $cities = array();

    while($row = mysql_fetch_assoc($result))
    {
       $cities[] = $row;
    }

    echo json_encode($cities);
    ?>

JSON Print:

[{"city":"Belgrade"},{"city":"Novi Sad"}]
2
  • 2
    data is an array, it doesn't have a .city property. $.each(data, function(i, itemData){ cities[i] = itemData.city; });. Commented Mar 24, 2014 at 15:13
  • Rookie mistake, but I'm rookie anyway. Thx mate! Commented Mar 24, 2014 at 16:37

2 Answers 2

1

Just loop the array and push

for (var i = 0; i < data.length; i++) {
    cities.push(data[i].city);
}
Sign up to request clarification or add additional context in comments.

Comments

0

As timeJV said just loop the array and add the cities to you array, here is an example of how it will be using the $.each, but the previous answer will do the work.

 $.each(data, function( i, itemData ) {
                     cities.push(itemData.city);
          });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.