0

I am trying to write a script to produce a chart using HighCharts. I have an issue with a call to my data which is causing an error.

SyntaxError: missing ] after element list

This is the code I am using:

var data1 = [<?php
mysql_select_db($database_test, $con);
$query_result = sprintf("SELECT AName FROM Answers WHERE AName IS NOT NULL GROUP BY AName");
$result = mysql_query($query_result, $con) or die(mysql_error());


while ($row_result = mysql_fetch_assoc($result)){
?>

[<?php echo $row_result['AName'];?>],

<?php
}
?>
]

Trying to debug it in Firefox dev console it points to the above code as the cause. Can anyone see why it is falling over with the error "SyntaxError: missing ] after element list.

If I hard code the data it works fine.

Many thanks for any help you can give.

DCJones
  • 3,121
  • 5
  • 31
  • 53

3 Answers3

1

Add the coma before the array except for the first one, it will do the trick.

But also take a look at json_encode.

var data1 = [<?php
mysql_select_db($database_test, $con);
$query_result = sprintf("SELECT AName FROM Answers WHERE AName IS NOT NULL GROUP BY AName");
$result = mysql_query($query_result, $con) or die(mysql_error());

$first = true;
while ($row_result = mysql_fetch_assoc($result)){
    if($first) {
         $first = false;
    } else {
         echo ', ';
    }
    echo '[' . $row_result['AName'] . ']';
}
?>
]
KyleK
  • 4,643
  • 17
  • 33
0

Per comments, it looks like AName is a alphanumeric string which needs to be wrapped in quotes.

<?php
    mysql_select_db($database_test, $con);
    $query_result = sprintf("SELECT AName FROM Answers WHERE AName IS NOT NULL GROUP BY AName");
    $result = mysql_query($query_result, $con) or die(mysql_error());
?>

var data1 = [
    <?php while ($row_result = mysql_fetch_assoc($result)) { ?>
        ["<?php echo $row_result['AName'];?>"], // <—— Wrap in quotes here
    <?php } ?>
];

Also, as KyleK pointed out, why aren't you using json_encode?

Community
  • 1
  • 1
rgajrawala
  • 2,148
  • 1
  • 22
  • 35
0

first of you will create the php array of database value which is needed. after this you will convert this it into json encode using j json_encode($array). then use the $.each() function for creating the high chart array value.

$(document).ready(function(){

var array = [];
array.push('apple');
array.push('apple');
array.push('apple');
alert(array);

});