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.

4

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have inserted type as contentType: 'application/json', in ajax call still it is giving same error
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.