I have a working connection between my json object and getJSON(). I can also sort the data i get once with this code, I sorted it on the \'name\' field of the array and it works
Do this:
var json = { users: [] };
var url="http://localhost/api/users.php";
$.getJSON(url,function(response){
json = response;
});
function sortJsonField(field){
function sortJson(a,b){
if(field == "id"){ return a.id > b.id? 1 : -1; }else
if(field == "job"){ return a.job > b.job? 1 : -1; }else
return a.name > b.name? 1 : -1;
}
// No need to assign this to a new array.
json.users.sort(sortJson);
showJSON();
};
function showJSON(){
// May empty the ul/ol before doing this? up to you..
$.each(json.users,function(i,row){
$("#output").append(
'- ' + row.id + row.name + row.job + '
'
);
});
};
EDIT: Also, the JSON structure is slightly incorrect...
Change this:
{"users":[
{"id":"1","name":"John","job":"worker"}
{"id":"2","name":"Mike","job":"innovator"}
{"id":"3","name":"Anna","job":"reader"}
]}
....to this:
{"users":[
{"id":"1","name":"John","job":"worker"}, // <--- Do you see the commas here?
{"id":"2","name":"Mike","job":"innovator"}, // <--- and here?
{"id":"3","name":"Anna","job":"reader"}
]}
The objects are well-formed, but that is not a valid array, so javascript breaks. Modify it and it should all work.
P.S This is the url of the website I used to check your JSON structure: http://www.freeformatter.com/json-validator.html