Reputation: 857
I have some jQuery that will change the contents of a select box depending upon the value of another select box (it uses AJAX). The PHP is returning the array how I want (sorted by TypeDescriptionData.name), but the list is getting re-ordered somewhere in the JS. Any ideas?
PHP Call:
public function get_descriptions_by_type($typeId) {
$this->autoRender = false;
$this->loadModel('TypeDescriptionData');
$data = array();
$this->TypeDescriptionData->contain();
$descriptions = $this->TypeDescriptionData->find('list', array('conditions' => array('type_data_id' => $typeId), 'order' => 'name ASC'));
if(isset($descriptions) && is_array($descriptions)) {
foreach($descriptions as $x => $y) {
$data[$x] = $y;
}
}
echo json_encode($data);
}
Here's the JSON right after the json_encode php call above:
{
"1":"FD 50",
"9":"Hypercom T4210",
"2":"Hypercom T7P",
"8":"Hypercom T7Plus",
"10":"Nurit 2085",
"11":"Nurit 8400",
"12":"Nurit 8400 Lite",
"17":"Other Terminal",
"13":"Verifone Tranz 330",
"14":"Verifone Tranz 380",
"15":"Verifone Vx510",
"16":"Verifone Vx510 LE"
}
Here's the JS:
$('#TypeType').change(function() {
$('#TypeDescription').find('option').remove().end();
$.ajax({
url:'/TypeData/get_descriptions_by_type/' + $(this).val(),
type:'POST',
dataType: 'json',
success: function( json ) {
console.log(JSON.stringify(json));
$.each(json, function(i, value) {
$('#TypeDescription').prepend($('<option>').text(value).attr('value', i));
});
}
});
});
And here's the JSON if I add "console.log(JSON.stringify(json));" immediately after the "success: function( json ) {" in the JS above:
{
"1":"FD 50",
"2":"Hypercom T7P",
"8":"Hypercom T7Plus",
"9":"Hypercom T4210",
"10":"Nurit 2085",
"11":"Nurit 8400",
"12":"Nurit 8400 Lite",
"13":"Verifone Tranz 330",
"14":"Verifone Tranz 380",
"15":"Verifone Vx510",
"16":"Verifone Vx510 LE",
"17":"Other Terminal"
}
Upvotes: 1
Views: 133
Reputation: 931
A json object is an associative array, so the two objects are actually equivalent. Basically the computer doesn't remember the order, just key/value pairs. If order really matters to you then you need to use some other kind of structure. For example you could embed an array:
{
"beaches" : [
{"key" : "1", "value" : "FD 50"},
{"key" : "2", "value" : "Hypercom T7P"},
{"key" : "8", "value" : "Hypercom T7Plus"}
]
}
Upvotes: 1