Craig Hooghiem
Craig Hooghiem

Reputation: 1282

jQuery AJAX not Working to Update City By Province

As the title may suggest, I have been using jQuery AJAX to try and pull a list of Cities from a database when a Province is selected.

I am using the following code:

$('#province').change(function()
{
    var province = $(this).val();

    /*$.get("<?php echo site_url('cottage/cities'); ?>?province="+province, function(data) 
    {
        console.log(data);
        for (i=0;i<=data.length;i++)
        {
            //$('#citydiv').append(data['city']+'<br/>');
            //$('#city').append('<option value="'+data[i]['city']+'">'+data[i]['city']+'</option>');
        }
    }); */
    $.ajax({
    url: "<?php echo site_url('cottage/cities'); ?>?province="+province,
    method: 'GET',
    dataType: 'json',
    success: onDataReceived
    }); 
    function onDataReceived(series) 
{
    console.log(series);

}   
});

And I also have a Province and City drop down associated with them. The problem is that I keep getting "undefined" returned, as it doesn't like the way my data is sent.

The data looks like:

[{"city_id":"1107","city":"Young's Point","province":"Ontario","lat":"44.490345","lon":"-78.236008"},{"city_id":"1108","city":"Zurich","province":"Ontario","lat":"43.421185","lon":"-81.624832"}]

Any help would be greatly appreciated!

Upvotes: 0

Views: 782

Answers (3)

Paul Dragoonis
Paul Dragoonis

Reputation: 2333

Try properly encoding your json response with www.php.net/json_encode

In your onDataReceived() function perform a check on this also to make sure it's valid data.

Even something simple like this would to to stop any JS errors from occuring.

function onDataReceived(series) {
    if(series.length  > 0) {
         // do your stuff
    }
}

Upvotes: 0

MvanGeest
MvanGeest

Reputation: 9662

Your data should look like

[
    {"city_id":1, "city":"Aberfoyle", "province":"Ontario", "lat":43.472996, "lon":-80.152603},
    {"city_id":2, "city":"Actinolite", "province":"Ontario", "lat":44.543221, "lon":-77.325813}
]

Don't put quotes around numbers, use brackets etc. json_encode is useful (as Christian Smorra stated).

Upvotes: 1

Christian Smorra
Christian Smorra

Reputation: 1754

json encoded strings look like this

{"a":1,"b":2,"c":3,"d":4,"e":5}

whereas you have square brackets try encoding your data in php with json_encode($array);

Upvotes: 2

Related Questions