I'm echoing json with php like so:
$jsonarray= array();
while($rs = mysqli_fetch_assoc($result)) {
$jsonarray["userName"]= $rs["userName"];
$jsonarray["UserGender"]= $rs["UserGender"];
$jsonarray["channel"]= $rs["channel"];
$jsonarray["channelName"]= $rs["channelName"];
$jsonarray["camonoff"]= $rs["camonoff"];
$jsonarray["rtccam"]= $rs["rtccam"];
$jsonarray["iswatching"]= $rs["iswatching"];
$jsonarray["iswatchingembed"] = $rs["iswatchingembed"];
$jsonarray["islisteningtoradio"]= $rs["islisteningtoradio"];
$jsonarray["statusmsg"] = $rs["statusmsg"];
$jsonarray["activity"]= $rs["activity"];
echo json_encode($jsonarray);
}
With an ajax call i get the string like:
$.get('lib/class/json.php', data, function(returnData) {
jsondata= returnData;
jsonupdateregion(jsondata);
});
I pass the received data to a function like:
function jsonupdateregion(jsondata) {
var regions = ["Lobby", "Noord-Brabant", "Groningen", "Friesland", "Gelderland", "Limburg", "Zeeland", "Overijssel", "Drenthe", "Noord-Holland", "Zuid-Holland", "Utrecht", "Belgie", "Duitsland"];
var i;
str= "";
for (i = 0; i < regions.length; i++) {
str += regions[i]
+ getCount(regions[i], jsondata);
}
console.log(str);
}
The above fuction has to call the following function for every region in the array regions and return the number of occurrences
function getCount(regions, jsondata) {
var count = 0;
for (var i = 0; i < jsondata.length; i++) {
if (jsondata.channelName[i] == regions) {
count++;
}
}
return count;
}
The above result in a " Uncaught TypeError: Cannot read property '0' of undefined"
When i use the json.parse on the data i get an error like: " Uncaught SyntaxError: Unexpected token {
The php file itself sends a header with: "header('Content-Type: text/html; charset=utf-8');"
What am i doing wrong here? When i use the json.parse i get an error stating an unexpectit token
I've altered the query on the server and it's now definitly outputting valid Json according to http://jsonlint.com/ .
if(isset($test)){
$sql = 'SELECT
userName,
UserGender,
UserRegion,
channel,
channelName,
camonoff,
rtccam,
iswatching,
iswatchingembed,
islisteningtoradio,
statusmsg,
activity
FROM
users';
$result=mysqli_query($conn,$sql);
$json = array();
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$json[]=json_encode($row);
}
}
mysqli_close($mysqli);
echo json_encode($json);
}
UPDATE:
The fault was in the javascript:
Had to change:
for (i = 0; i < obj.length; i++) {
if (obj.channelName[i] == regions) {
count++;
}
TO:
for (i = 0; i < obj.length; i++) {
if (obj[i].channelName == regions) {
count++;
}
And in php revert back to echoing echo json_encode($json);
var regions = [...]withvar regions = {...}