Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop Chrome and Opera sorting JSON objects by Index ASC?

I've got a problem.

Using ajax I sent a correctly formed JSON object using:

            $.ajax({                 type: "POST",                  url: SITE_URL+'/data.php',                 dataType: "json",                 data: { ajax: 1 },                 success: function(data) {                     console.log(data);                 }             }); 

However, Opera and Chrome, although receiving the same object, print out the object in an incorrect order, it seems like they both perform a sort by ID number instead of just leaving it alone!

Is there a way to stop this auto sort?

Edit, after finding out it is a sort by index number I'm thinking the best method might be to not use the index for storing the object_id and instead store the id number which I want to order the object by.

However I would still like to know if there is a way to stop the sort.

Thank you

Edit2, I'll just like to note that I'm going to work on a different way of doing this, as I feel like I'm abusing objects with this method. However I'd still like to understand why Opera and Chrome feel it is their right to change the order of my objects IDs:

The problem would be me trying to save processing power, lets say we have people with an ID,

1.John, 2.Frank and 3.Sally. However each of these people have a hight property set (and other things). 1.John.180, 2.Frank.220, 3.Sally.150. To save on processing, my I request the result of people be sorted by their height so I get an array of 2, 1, 3 with their other properties. I JSON this array and send it to the browser.

Now FF will keep the new order People[1] would still be John but in a For n as person loop they'll be out of order.

If I can't get around this I'll just have to not bother sorting at the SQL stage and add extra looping and sorting into an array in the JS stage although I wanted to avoid more stress on the browser as its already a Js heavy page.

Many thanks

like image 951
Dorjan Avatar asked Feb 16 '11 18:02

Dorjan


2 Answers

Had same problem, followed dmc's solution but just added a space in front of the int value to make it a string.

The advantage of using a space rather than another non numeric character is that the subsequently POSTed value can be used directly in a mySQL search clause without having to remove it again.

like image 100
FarnhamBee Avatar answered Oct 11 '22 18:10

FarnhamBee


Different browsers handle objects in different ways, my fault was to try and use the order I built an object as a reference where I shouldn't.

like image 32
Dorjan Avatar answered Oct 11 '22 19:10

Dorjan