1 Vote Vote

Populating a drop down list using jQuery getJSON not working

Posted by topdog 516 days ago Questions| using getjson jquery All

Hi guys, I am trying to send a variable with jQuery's getJSON function but it doesn't seem to be going through, I am also unsure of how to get the variable I have just sent in the waiting PHP file, do I just reference it via the name I sent it as, for instance if I send a variable called 'test', can I get it like this, $_POST['test'] on the other side? or how exactly would that work?

I am trying to populate a drop down list using the method below, any advice on improving the code would be greatly appreciated!

Here is what the PHP returns:

[{"city":"One"},{"city":"Two"},{"city":"Three"},{"city":"Four"}]

jQuery:

//get the cities
$("#province").live('change', function(){
    var test = $('#province').val();
    //alert(test);

    $.getJSON("cities.php", test, function(data){

    //clean out the select list
    $('#city').html('');

        //run the loop to populate the drop down list
        $.each(data, function(i, data) {
            var city = data.city;     

            $('#city').append(
                $('<option></option>').html(city)
            );
        });
    });
});

PHP:

$province = $_POST['test'];

//mySQL query here

$myarray = mysql_fetch_array($query, true);
$string = explode(',', $myarray['cities']);

foreach($string as $key=>$value) {
    $string[$key] = array('city'=>$value);
}

$json = json_encode($string);
echo $json;

What could I be doing wrong?

Thanx in advance!

Originally asked by: kielie on Stack Overflow

Discuss Bury


Who Voted for this Question