up vote 1 down vote favorite
share [g+] share [fb]

I am using php and JS in my code.My requirement is I need to fetch the value from my-sql database and display into drop down list dynamically.I am populating the dropdown with JS but fetching the value with php(a usual thing). So the problem I am facing is once I get the value from php code and encode it using json_encode to access that array in JS it shows me value like [object Object].

Please help.. Thanks.

Sample Code:-

<?php
$result=mysql_query("select Location from servicelist")or die (mysql_error());
while($row = mysql_fetch_array($result))
 $output[]=$row;
   $row=mysql_fetch_assoc($result);
$output[]=$row;

 ?>
<script language="javascript">
function addOption_list(selectbox){
<?php echo 'var month='.json_encode($output);?>

for (var i=0; i < month.length;++i){
addOption(document.drop_list.AreaList, month[i], month[i]);
//Once the value of the area will get selected we will call sub area based
//on the area selected from the db
}
addSubAreaList();
}
link|improve this question

25% accept rate
show us the generated code (post PHP execution) – Janus Troelsen 31 mins ago
Hi Janus, Please check the edits in the code.. – Abhinandan Sahgal 18 mins ago
feedback

1 Answer

Objects in JavaScript are similar to "associative arrays" in PHP. If you have an object and you try to write it on the console, it will evaluate to the string "[object Object]". If you want a proper string representation, JSON encode it again in your JavaScript using JSON.stringify.

link|improve this answer
I tried var myJSONText = JSON.stringify(myObject, replacer); So what should be that replacer?? And if I try the replacer as a string it doesnot work.. – Abhinandan Sahgal 12 mins ago
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.