Kraishan
Kraishan

Reputation: 455

Convert PHP objects array to javascript array

I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:

The instantiate.php includes files like Jquery and another JS file.

<?php
    require_once("../../include/instantiate.php");    
    $photos = Photos::get_all();
    $JSPhotos;
    foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>

<script type="text/javascript">
    $(document).ready(function() {
        var photos = <?php echo json_encode($JSPhotos); ?>;
        for(var i = 0; i <= 10; i++)
        {
            create_image("../"+photos[i]);
        }
    });

This does not work. Anyone got a solution? Solution in Jeroen's Post!

New Problem;

In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?

Script in the javascript part:

$(".imgid").click(function() {
    alert("hey");
});

Upvotes: 1

Views: 148

Answers (1)

jeroen
jeroen

Reputation: 91734

You are not assigning anything to your variable.

You probably want:

$JSPhotos = array();
foreach($photos as $photo) {
  $JSPhotos[] = $photo->source_path;
}

Or something similar.

Upvotes: 1

Related Questions