I have the following json encoded array which I pass to JQuery as follows, and everything works fine when when there are elements in the array. However, there are times when the array might be empty depending upon a users selections, and that is where my script breaks down:
PHP
$myleaderarray = [{"Week_count":"3","Userid":"102","Username":"gsd555","MedCondPrimary":"Diabetes"},{"Week_count":"0","Userid":"216","Username":"gsd3","MedCondPrimary":"Cardiac Respiratory"}]
$count = count($myleaderarray); //1
JQ
var myleaderarray = <?php echo $myleaderarray; ?>; // this passes the array as expected
console.log(myleaderarray.length); //2
This is what I see in the console when the json_encoded array is empty
JQ
var myleaderarray = ;
"Unexpected token ';'"
I can't seem to test for this error in JQ so must I do this on the server-side, or am I completely missing something? Thanks for the help.
json_encode
. Your problem is that your string is empty, but it should be[]
. if you pass a proper array to json_encode is should always work. but i cant really tell you what you have to do because the code you posted here is messed up