简体   繁体   中英

My Image sources (src) are a $file_path php echo, how I can pass the clicked $file_path to javascript?

So I have the below code to put files from folder as a gallery images, using loop

<?php
        $path = "server/php/files/"; // path to images folder
        $file_count = count(glob($path . "*.{png,jpg,jpeg,gif}", GLOB_BRACE));
        if($file_count > 0)
        {
            $fp = opendir($path);
            while($file = readdir($fp))
            {
                $ext = pathinfo($file, PATHINFO_EXTENSION);
                $ext_array = ['png', 'jpg', 'jpeg', 'gif'];
                if (in_array($ext, $ext_array))
                {
                    $file_path = $path . $file;?>
                    <div class="col-md-4 col-xs-6">
                        <button href="" id="img1" style="background-color: #ffffff; border: none;color: white;padding-left:3.0rem;text-align: center;text-decoration: none;display: inline-block;font-size: 16px; float:left;" onclick="myFunction(this.src)" title="My Favorites" data-gallery><img class="floating-box" src="<?php echo $file_path; ?>" class="img-responsive" /></button>
                    </div>
                <?}
            }
            closedir($fp);
        }
        else
        {
            echo "Sorry! There are no images in the gallery!!!";
        }
        ?>

The onclick="myFunction(this.src) should pass the src parameter to the onclick function, but the result I get is undefined

<script>
        function myFunction(element) {

            $.ajax({
            type: "POST",
            cache: false,
            url: "data_change.php",
            data: {value: element}, //send a new value to the "my_backend.php" script
            beforeSend: function (html) {
                //show a preloader here
            },
            success: function (html) {
                //do something if request is successfully completed
                alert(element);
            }

        })


        };




        </script>

This passes the button element, not the image element inside it, where you have your src.

You can do something like this to get what you need:

data: {value: element.children[0].src},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM