1

I am returning an array of banners using json_encode like this from the AJAX handler code (PHP)-

echo json_encode(array("bannersData" =>$bannersData));

The order of data is proper upto here, when it is echoed.

However, in the AJAX response handling code (javascript part), I get a different sorting of the returned object (sorted by banner ID it seems) in chrome Version 26.0.1410.64 m. I am not sure whether we have any option to enforce keeping the original sort order intact.

Here is the code -

$.ajax({
type: "POST",
async: false,
url: posturl,
data:postdata,
dataType: "json",
success: function(msg){

    if($.isEmptyObject(msg.bannersData))
    {
        bannerOptionsHtml = "No Banner available";  
    }
    else
    {
        /*getting unexpectedly sorted result here*/

    }

});

Example data-

Input

When I do echo json_encode(), following is original ordering of data -

'fggd'             [12658]
banner 2           [12653]
Copy 2 of banner 1 [12655]
Copy 3 of banner 1 [12656]
Copy 4 of banner 1 [12657]
sdfds = 'xyz'      [12654]

Outputs

But, following is what I get in AJAX response -

In chrome (sorting happening based on banner ID, it seems - R.H.S. column below is banner ID)

Test                [12652]
banner 2            [12653]
sdfds = 'xyz'       [12654]
Copy 2 of banner 1  [12655]
Copy 3 of banner 1  [12656]
Copy 4 of banner 1  [12657]
'fggd'              [12658]

In firefox (as expected)

'fggd'             [12658]
banner 2           [12653]
Copy 2 of banner 1 [12655]
Copy 3 of banner 1 [12656]
Copy 4 of banner 1 [12657]
sdfds = 'xyz'      [12654]
Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144

2 Answers2

0

Did you try to convert numeric key to String in your PHP array? It seems that Chrome sorts int keys array (same issue with opera)

aureg
  • 1
  • 1
0

Can you provide the format of the JSON object you actually have? I'd bet £1 that the bannersData is actually being transferred across as an array and not as an object.

There is a standard that browsers follow to re-create objects from JSON strings, and this standard orders browsers to keep the key-value order intact. This, however, is not the case for arrays, and there is absolutely no standard on those. Browsers, therefore, have differed on this.

This isn't an obscure fact: How do you stop Chrome and Opera sorting JSON objects by Index ASC? is a duplicate of your question (and I will probably vote it as such).

Two solutions: transform your array from PHP into an object with key-value pairs (even if the keys are numeric!) to keep the order, or understand that the order will not be kept across all browsers. The first option requires no JS code change unless if you are using for integer-iterated loops (for (var i = 0; i < array.length; i++) {, at which point you will need to iterate on the object's keys rather than the object itself.

Community
  • 1
  • 1
Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66