1

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);

6
  • 1
    first of all complete quotes at Friesland", like this "Friesland", Commented Dec 7, 2014 at 18:12
  • Have you tried replacing var regions = [...] with var regions = {...} Commented Dec 7, 2014 at 18:13
  • The quotes is a typo here and is not the cause. Chenging the [ to { doesn't do it either. I get an error like: " Uncaught SyntaxError: Unexpected token , Commented Dec 7, 2014 at 18:39
  • How many records are you changing into a JSON? The fact that you are using a while loop seems there's more than one. Commented Dec 7, 2014 at 18:40
  • @mickey there are about 100 records. You can see the result for now at transonly.nl/lib/class/json.php?test Commented Dec 7, 2014 at 18:44

1 Answer 1

2

At first, try to give jquery a hint, that json is sent and see, what it receives in your browser console (http://api.jquery.com/jquery.get/)

$.get('lib/class/json.php', data, function(returnData) {
    var jsondata = returnData;
    console.log(jsondata); 
    jsonupdateregion(jsondata);
}, 'json);

it should output an object or just a string.... eventually your php echoes some new lines or other craty things before or after the answer. What about the charset? Is your server maybe answering in iso-something? Then js would fail decoding your jsonstring if there are some crazy chars (ü, ß, ç)

Last thing

$jsonarray = array();     
while($rs = mysqli_fetch_assoc($result)) {
    $jsonarray[] = $rs; //add an element.. do not overwrite it
}
echo json_encode($jsonarray);   
Sign up to request clarification or add additional context in comments.

7 Comments

The server is echoing: UTF8. The php has a content header of: header('Content-Type: text/html; charset=utf-8'); As for the array... that gives me only [][][][]. if you want to examine the output of the php you can see it for now at: transonly.nl/lib/class/json.php?test
The chekc my "last thing"... you are echoing many objects, but with no array around it.... it has to look like this [{...},{...}] bit yours looks like this {...} {...}
Ok, i'm echoing the brackets now with it as you can see at transonly.nl/lib/class/json.php?test . Again with the result: Uncaught TypeError: Cannot read property '0' of undefined.
too much escaping... you are echoing ["{\"use... it should be [{"use..., just try my second snipped in the answer
whatever, please just try the second snippet.... don't echo in the loop, you last "object" should not be followed by a ,, the other ones should.... all objects should be encapsulated in an array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.