Problem: returns array, but not in json.
Result: must return array with in array. outer array has key with numbers and value is array with keys “ID” and “NAME” and there values are assigned from database.
$i = 0;
$json_values = array();
while($sctg = mysql_fetch_assoc($get_sctg)){
$json_values[$i] = array("ID" => $sctg['ID'], "NAME" => $sctg['NAME']);
$i++;
}
echo json_encode($json_values);
Your code is perfectly fine – you just misunderstood the different between arrays and objects in JavaScript.
This is JSON containing an array with three elements. Each element is an object with the properties
IDandNAME.Let’s assume that array is stored in
data. You can iterate over the objects in that array with a simpleforloop:I guess you expected your JSON to look like this:
This would actually be bad since objects in JavaScript are not ordered (even though they actually are in most browsers, but that’s not guaranteed!). So when iterating over the rows in such an element (using
for(var key in data)), you would not necessarily get the row with ID=4 first just because its key is zero.However, if you really want an object instead of an array for some reason (you don’t!), you could always cast the array to object:
As a side-note, usually it’s a good idea to have an object as the top-level element in JSON for security reasons (you can redefine the array constructor and then include something with a top-level array with a script tag and thus access data usually protected by the same origin policy if it was accessed by an XHR request), so I’d change the PHP code like this: