How do I pass a string from PHP to a JavaScript function?

Solution 1:

When passing a PHP string into an inline JavaScript function, you need to properly escape quotes:


echo "<td onclick='print_(\"" . $file[$i]->Name . "\");'>" . $file[$i]->Name . "</td>";

Explanation:

The outer HTML attribute uses single quotes (‘) for onclick.

The JavaScript string argument uses double quotes (“) to avoid conflicts.

Concatenate the PHP variable $file[$i]->Name inside the quotes.

Ensure $file[$i]->Name does not contain quotes, or escape them using addslashes():


$name = addslashes($file[$i]->Name);
echo "<td onclick='print_(\"$name\");'>$name</td>";

✅ This prevents syntax errors in the generated HTML/JavaScript.

Solution 2:

Instead of embedding inline JavaScript with PHP variables, you can generate the JS dynamically using jQuery, giving you more flexibility:


<?php
$scriptCode = "";

for ($i = 0; $i < count($files); $i++) {
    echo "<td id='print_td$i'>" . htmlspecialchars($files[$i]->Name) . "</td>";

    // Build dynamic JS for each cell
    $scriptCode .= '$("#print_td' . $i . '").click(function() {
        var id = ' . $i . ';
        // Call your JS function here, e.g.:
        // print_(id);
    });';
}
?>

<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    <?php echo $scriptCode; ?>
});
</script>

Explanation:

Each

gets a unique ID (print_td0, print_td1, etc.).

$scriptCode accumulates JavaScript for each cell dynamically.

jQuery binds a click event to each cell, allowing you to call any JS function (e.g., print_(id)).

Using htmlspecialchars() ensures cell content is safe for HTML output.

✅ This approach separates HTML from JS, making it more maintainable and flexible than inline onclick handlers.