Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery getJSON sorts my data by id automatically

I have a combo box that triggers a jquery function on change, it calls a php script which brings the results from the database sorted by name not by id (table cities) and creates a json file with the id and the name of the city. The problem comes with a $.getJSON(url, data) function, it retrieves all the json encoded data fine, but it is seems to be sorting the data automatically by the id

for instance if the php page generates

id  name
3   Dania Beach
1   Miami
2   Weston

after jquery getJSON it sorts it by id

id  name
1   Miami
2   Weston
3   Dania Beach

Is there a way to disable sorting? or how can in preserve the order by name?

like image 741
gabo84 Avatar asked Sep 24 '12 22:09

gabo84


1 Answers

This is an associative array: order does not matter. The following JSON objects are equivalent:

{
    "3" : "Danie Beach",
    "1" : "Miami",
    "2" : "Weston"
}

{
    "1" : "Miami",
    "2" : "Weston",
    "3" : "Danie Beach"
}

If you need an ordering, you should instead embed an array within the JSON:

{
    "beaches" : [
        {"key" : "3", "value" : "Danie Beach"},
        {"key" : "1", "value" : "Miami"},
        {"key" : "2", "value" : "Weston"}
    ]
}

Example Usage:

jQuery.ajax({
    ...
    dataType: 'json',
    success: function(data) {
        jQuery.each(data.beaches, function(i, beach) {
            alert(i+': beach['+beach.key+'] = '+beach.value);
        });
    }
});
like image 52
Joe Coder Avatar answered Sep 28 '22 08:09

Joe Coder