1

I have a problem with my javascript array. Bellow my code:

$namen = array();
    $mainimg = array();
    $sql1 = mysql_query("SELECT * FROM image WHERE id = ".$id.";");

        echo "<div class='normal'>";

        while($row = mysql_fetch_array($sql1))
        {
            $namen[] = $row['bild']; 
            $mainimg[] = $row['mainimg'];
            $number_array = count($namen);
            ?>
            <script type='text/javascript'>
            <?php
            for($a=1; $a <= count($namen); $a++){
                $php_array = array($a => $row['bild']);
                $js_array = json_encode($php_array);
                echo "var javascript_array = ". $js_array . ";\n";
                echo "document.write(javascript_array + '<br />');";

                }
            ?>
            </script>
        }

Now I get [object][Object] in the browser, but I wanted to printout the elements, the name of the pictures. What can I do?

Thanks for your help in advance.

Regards, Yanick

1
  • 1
    i dont see the point of the js here at all, you could simply use php for it all Commented Aug 8, 2013 at 21:09

2 Answers 2

1

You're trying to print a Object as a string. What you need to do is to access your properties directly from the object.

<script>
<?php $data = array('foo' => 'bar'); ?>
var my_js_var = <?php echo json_encode($data); ?>;
</script>

With this script, you can access your values like this:

document.write(my_js_var.foo); // writes 'bar'
3
  • Perfect!!! :-) It works. No I get ["test1.jpg"] for example. Is there an easy way to get only test1.jpg? Commented Aug 8, 2013 at 21:19
  • You could test if $php_array has a single value, but this would increase your code and may not be worth it. Unless it will always be a single value, so you don't need to use an array, or even JSON, just pass the value to the JS var, with single quotes, and it will be a string. Glad it helped. If it fits, consider accepcting the answer :) Commented Aug 8, 2013 at 21:23
  • I would like to make a image gallery so I have to put the values into an javascript array. :-( I have it now like this: $php_array = array($a => $row['bild']); .... $a++; Now I get eg. {"1":"test.jpg"} in the browser. Can I get just test.jpg with document.write. I would like to test it, because afterwoods I need the test.jpg as a source for the picture which changes by clicking on next- or prev-button Commented Aug 8, 2013 at 21:30
0

You'll need to loop through the array and output the fields you want for each item. You're currently printing out the string version of an object in JavaScript, which is always [object Object].

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.