javascript/ php/ html/ string/ echo

I'm trying to echo a string in PHP as a string variable in a JavaScript function. It doesn't output as desired. How do I fix this?

<?php
    $example1 = "example 1";
    $example2 = "example 2";
    $example3 = "example 3';
    $string = $example1.", ".$example2.", ".$example3;
    echo "<script>function testFunction(string) {console.log(string);}</script>";
    echo "<button onclick='testFunction(".$string.")'>Test</button>";
?>

Desired output: <button onclick='testFunction("example 1, example 2, example 3")'>Test</button>

Actual output: <button onclick='testFunction("example 1" example 2= example 3=)'>Test</button>

Inline handlers are horrible practice. They have very ugly quote escaping issues (that you're running into here) and have a demented scope chain. There should be no reason to use them in modern JavaScript. Consider passing the values to the HTML some other way, and then attaching the handlers properly using JavaScript instead.

For example, you could use data attributes for each button, or you could echo JSON into a script tag that contains the parameters:

$button_data = array(
    'example 1, example 2, example 3'
    // add more button data here as needed
);
<script type="button-data">
<?php echo json_encode($button_data) ?>;
</script>

Then read it in JS and attach listeners:

const buttonData = document.querySelector('script[type="button-data"]');
// change this selector as needed
// to select only the buttons you care about
const buttons = document.querySelectorAll('button');
buttons.forEach((button, i) => {
  button.addEventListener('click', () => {
    testFunction(buttonData[i]);
  });
});

You can use the below code for doing it.

<?php
$example1 = "example 1";
$example2 = "example 2";
$example3 = "example 3";
$string = $example1 . ", " . $example2 . ", " . $example3;
?>
<script>
function testFunction(string)
{
    console.log(string);
}
</script>
<button onclick='testFunction("<?php echo $string; ?>")'>Test</button>

暂无
暂无

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.

Related Question Problem echoing php string as javascript function Parse Int and String into parameter of onclick function in JavaScript javascript onclick function with parameter Echoing javascript with events and function calls with parameters in PHP Passing parameter as a string containg white spaces in javascript's onclick function javascript onclick function works when parameter is integer but not string? How to send php variable onclick of button to javascript function as parameter passing parameter to javascript onclick function Pass a string parameter in an onclick function Echoing php inside javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM