I have a php script that fetches data from a DB, the result set is returned in a particular order, e.g.
Name: John, Age: 21, Address: 1234 Fifth Ave.
I verified the order while debugging. The result set is then pushed into an array, which is then encoded as a json object and passed to my jquery script through an AJAX request.
var resultSet = [];
$.ajax({
async: false,
url: 'scripts/getData.php,
dataType: "json",
success: function(data) {
/* Store the pieces of the array */
resultSet = data["php_resultSet"]; //<--Breakpoint here shows the resultSet sorted, if order is preserved here, my problem will be solved.
}
});
However, when I get my data back and analyze the array, it is sorted, e.g.
Address: 1234 Fifth Ave., Age: 21, Name: John Age: 21
I want to preserve the order of the original result set, is there an option I have to set in order to do that? Help is appreciated.
UPDATE:
Here is a snippet of the PHP code that builds the array and encodes it
$data = array ( "otherData" => array(), "php_resultSet" => array() );
while ( $row = sqlsrv_fetch_array ( $stmt, SQLSRV_FETCH_ASSOC ) ) {
//Push the entire row to the result set array
array_push ( $data["php_resultSet"], $row );
}
asort($someData);
foreach ( $someData as $key) {
array_push ( $data["otherData"], $key );
}
return json_encode($data);//<--At this point, even though the I sorted $someData before pushing it to the $data, the php_resultSet maintains its sorted order.
When encoding a hash (associative array) into JSON, the order of key/value pairs is not guaranteed to be preserved due to differences in how a hash is represented in the source language. For example, hashes in Perl are stored in such a manner as to optimize storage requirements at the expense of field order.
Having said that, there are several approaches you can take to have JavaScript reorder the AJAX result, one being to return the result along with the expected order of presentation, as in:
And then use it to either reorder the records before or while you populate the table on which they are expected to appear.
Another approach might be to append a value to each field name in each record which can be used to order them after retrieval and then, before display, removing the ordering value from the field name.
So on the server after converting the result into JSON, add a prefix from “aa_” for the first fieldname, incrementing the prefix for each succeeding field name up to “zz_”. So if the first two field names are “Name” and “Address” then become “aa_Name” and “ab_Address”.
Then just before adding the record to the table at the client, sort the fields by field name and then remove the prefix using
fieldName=fieldName.substring(3).