1

Possible Duplicate:
Sorting a JavaScript object

I have a json data like this

[
  {
    "name":"anand",
    "type":"0"
  },
  {
    "name":"bajaj",
    "type":"0"
  },
  {
    "name":"cat",
    "type":"1"
  }
]

I populate these data in a table with header, name and type.

I have stored these data in a javascript global array. Now i have to sort that global array according to key.

For example when i click the name it has to sort according to name and same for type.

I have tried many things but it is giving sort is not a function error.

var data_obj= [];  // declared a global variable 

 $.ajax({url: url,
         type:"post",
         data: "folder="+folder,
         success: function(data){
             data_obj = data // here i store returned json data in a global variable 
         }  
 });

a simple sort function

 data_obj.sort(function(a, b){
     return [a.name] < [b.name] ? -1 : 1;
 });

But it is giving me sort is not a function. Please help me in sorting according to key.

Community
  • 1
  • 1
Ananda Kumar
  • 49
  • 1
  • 7

1 Answers1

1

Presumably the server is sending the JSON back with the wrong Content-Type (it is common for people writing PHP to forget to override the default HTML content type with header('Content-Type: application/json');).

This would result in data being an HTML DOM instead of an Array inflated from JSON, so it wouldn't have a sort method.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I have inserted type as contentType: 'application/json', in ajax call still it is giving same error – Ananda Kumar Dec 03 '12 at 10:15
  • @user1403248 — The `contentType` property is documented such *When sending data to the server, use this content type*. It doesn't make any difference to the response (unless the server reacts to getting a JSON *request* by 500ing or otherwise not giving you the data you want at all). It is the HTTP Content-Type header in the **response** you need to change. – Quentin Dec 03 '12 at 10:20