1

I am trying to make a website which will basically have a lot of buttons that will execute a particular PHP file on click and show their results on an empty box on the same screen. These PHP files are present in a directory test_scripts in the same directory as index.php.

I thought that the obvious step would be to create a loop that will iterate over those files and create their ui dynamically. So I wrote the following PHP code in the middle of index.php

#Index.php
...
 <?php
    $dir_itr = new DirectoryIterator("test_scripts");
    foreach ($dir_itr as $file) {
        if ($file->isFile()) {

            $filename = $file->getFilename();
            $formattedFileName =
                '<button
                     class="box button is-large is-fullwidth is-primary is-light"
                     onclick="loadScriptFileData($filename)">
                               $filename
                 </button>';
            print $formattedFileName;
        }
    }
?>
...

The loadScriptFileData() is a JavaScript function written in a script tag present in head:

<!--index.php-->

<script>
    function loadScriptFileData(filename) {
        alert(filename);
    }
</script>

The for each loop is running correctly, but the JavaScript function and the generated HTML is not working correctly. There are the expected number of buttons on the page, but each button just has the name as the word "$filename" and not the actual expected filename. The case is worse with JavaScript, which straight out does not work and gives the error in the console as Uncaught ReferenceError: $filename is not defined at HTMLButtonElement.onclick ((index):71)

Why is the $variable not getting converted to a string? I even tried the toString() function, but still no good. Am I doing it wrong?

1
  • What have you tried to make this work? Is that a JS problem, or a PHP problem? Hint: check this by inspecting the markup to see what is put there Commented Apr 1, 2020 at 16:41

3 Answers 3

1

Variables are not parsed/interpreted when using single quotes.

Replace

$formattedFileName= '<button 
  class="box button is-large is-fullwidth is-primary is-light" 
  onclick="loadScriptFileData($filename)">$filename</button>';

with

$formattedFileName= "<button 
  class=\"box button is-large is-fullwidth is-primary is-light\" 
  onclick=\"loadScriptFileData('$filename')\">$filename</button>";

and everything should be working as expected.

Sign up to request clarification or add additional context in comments.

6 Comments

You can also use ' for the html attributes instead of escaping the double quotes. Or even better, close the PHP block ?> <button...></button> <?php. Then they can remove the print-line after as well.
Right, personally I like to have double quotes for html attributes
Both of you guys are awesome! thanks, this worked. i actually figured out about the double quotes and was able to make the ui work, but the js call was still not getting executed. why does it needed those extra ' $filename '?
@MagnusEriksson can you add your alternate approach as an answer as well? I want to learn more about it
@anshsachdeva - It's JS 101. When passing a string as an argument, it needs to be quoted: foo('bar'). Your code would produce: foo(bar) which JS would interpret as you trying to pass the value of a JS variable called bar (but in your case, it would be the filename)
|
1

Another option (which is my personal preference) is to end the PHP block when outputting HTML and just echo the PHP variables where needed:

if ($file->isFile()) {
    $filename = $file->getFilename();
    // Let's end the PHP block
    ?>

        <button class="box button is-large is-fullwidth is-primary is-light"
            onclick="loadScriptFileData('<?= $filename ?>')">
            <?= $filename ?>
        </button>

    <?php // Open the PHP block again
}

The upside with this is that IDE's will syntax highlight the code properly (which most IDE's don't do for HTML inside quotes in PHP).

You also don't need to escape quotes or manually print the content since it gets outputted straight away.

Comments

0

It's a personal preference, but I recommend either concatenation or curly braces:

Using curly braces (note: must wrap with double quotes):

$formattedFileName =
    "<button
        class="box button is-large is-fullwidth is-primary is-light"
        onclick="loadScriptFileData({$filename})">
        {$filename}
    </button>";

Using concatenation:

$formattedFileName =
    '<button
        class="box button is-large is-fullwidth is-primary is-light"
        onclick="loadScriptFileData(' . $filename . ')">
        ' . $filename . '
    </button>';

Yes, you can use variables in a string in PHP if you use double quotes, and there are certainly many people that like doing that. To me, it seems cleaner and less error-prone to use one of these two methods.

Using double quotes causes you to either use single quotes for HTML attributes or forces you to escape them.

Not using concatenation or curly braces can cause issues if you don't want a space after the variable:

$var = 'Pizza';
echo "$vars are awesome!" // Not the best example, but you get the idea

Bottom line, it's a personal preference. But as stated in the other answer, you can't use variables in a string if enclosed by single quotes.

3 Comments

I actually think your last example is a pretty spot on example of a real world case where it would fail.
@kerbholz is right .The curly brace example is not working for me and is directly printing {$filename}
Ah, duh. Yes, I've updated my answer. I'm a concat guy myself, since I like single quotes - forgot braces required double quotes too.

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.