0

I am iterating through a php array to display a list of photo filters. I need to be able to pass the selected filter name to my javascript function to load it, for now I am only able to get the $i id but the full filter name would be so much more easier.

How can pass $filters[$i] to getFilterName()?

<?php
    for ($i = 0; $filters[$i]; $i++)
    {
        if (strpos($filters[$i], '.png'))
        {
            ?>
            <!-- get php variable for javascript : -->
            <div id="filter-target" style="display: none;">
                <?php
                    echo htmlspecialchars($i);
                ?>
            </div>
            <!-- ... -->

            <?php
            echo '<div tabindex="-1" class="filter_box" onclick="getFilterName('.$i.')">';
                echo '<img class="filter" src="pictures/filters/'.$filters[$i].'"/>';
            echo '</div>';
        }
    }
?>

Thank you!

2
  • So on click event, you are unable to pass name of image is it? Commented May 13, 2019 at 12:06
  • @quickSwap absolutely Commented May 13, 2019 at 12:07

1 Answer 1

4

Because the filename is a string, you need to escape it in ' ' like so:

<?php
    for ($i = 0; $filters[$i]; $i++)
    {
        if (strpos($filters[$i], '.png'))
        {
            ?>
            <!-- get php variable for javascript : -->
            <div id="filter-target" style="display: none;">
                <?php
                    echo htmlspecialchars($i);
                ?>
            </div>
            <!-- ... -->

            <?php
            echo '<div tabindex="-1" class="filter_box" onclick="getFilterName(\''.$filters[$i].'\')">';
                echo '<img class="filter" src="pictures/filters/'.$filters[$i].'"/>';
            echo '</div>';
        }
    }
?>

Otherwise it would treat the string as a variable name in JavaScript and wouldnt fint it because it doesnt exist.

2
  • Amazing! Thank you so much Maurice Commented May 13, 2019 at 12:08
  • No problem @Martin. Glad I could help out. Feel free to accept my answer if it helped. Commented May 13, 2019 at 12:10

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.