liseHassler liseHassler - 23 days ago 9
PHP Question

PHP: single and double quotes issue with dynamic onclick buttons

I'm looping through an array of actions to generate

buttons. Each button must call a JavaScript
function, passing two parameters as arguments : 1. the action to be performed and 2. their ID to update the buttons once the function has been called.

PHP code (generate the buttons)

$actions = array('follow', 'add_friend', 'send_message');

foreach ($actions as $value) {
$id = $value."button";
echo "<button id='$id' class='action_button' onclick='ajax($id,$value)'>$value</button>";

JavaScript function to be called :

function send_ajax(elem, action) {
console.log(elem, action);

When clicking the buttons generated using PHP, I get the following:

Uncaught ReferenceError: follow is not defined at HTMLDivElement.onclick

Obviously this is happening because i'm not wrapping
inside quotes when creating the buttons so JavaScript gets their values (say 'follow_button' and 'follow'), but is still looking for their values, treating them as JavaScript variables.

onclick='ajax($id,$value)' //here is my problem

However I can't seem to find the proper way to wrap my arguments inside quotes without creating a PHP parse error as I've already used both single and double quotes when echoing the buttons.

How can I generate my buttons so they can properly pass their arguments to
function ? If I'm going all wrong, which approach should I use ?

Answer Source

You need to use escape the quotes. Here is a previous example on how to use quotes inside quotes. How to escape quotes in inline styles?

You can also use slashes to determine quotes inside of quotes. How to escape double quotes in JSON