2

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();
}
2
  • show us the generated code (post PHP execution) Commented Feb 29, 2012 at 12:47
  • Hi Janus, Please check the edits in the code.. Commented Feb 29, 2012 at 13:01

2 Answers 2

1

In PHP mysql_fetch_assoc($result); returns an associative array, so your month variable in JavaScript will be in the format:

var month = [{field: 'value', otherField: 'value'}];

your loop therefore needs to use something like:

var areaList = document.drop_list.AreaList;
for (var i=0, len = month.length; i < len; ++i){
  addOption(areaList, month[i].field, month[i].otherField);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It worked.. The only thing I was missing was the column after the month field of which I need to fetch the value. Thanks a lot..
No problem, re-reading your PHP, the query is only picking out one field, so you could make it simpler by using $rows = mysql_num_rows($result); for($i = 0; $i < $rows; $i++) $output[] = mysql_fetch_result($result,$i,0); then the month variable in the JavaScript would be a string array, so you could use the JavaScript you originally had.
0

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.

3 Comments

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..
How do we got that PHP array into a JS array here?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.