PHP variable binding issue with html from controller for ajax response


$html = "";
$user_id = 10;
$by = 'By Aaron';
$getLedgerData = "getLedgerData('" . $user_id. "','" . $by . "')";
$html .= "<a onclick=" . $getLedgerData . "></a>"
print_r($html);die; //  result shows: getLedgerData('10','By Aaron')

When I passed $html to ajax response and set from there to a respected HTML tag. It will also seem like the above result. But When the HTML page is refreshed then I can see the below error and HTML from inspect element.

<a onclick="getLedgerData('10','By" 'Aaron')=""></a>
Uncaught SyntaxError: Invalid or unexpected token (at 0:1:35)

The result should be like this:

<a onclick="getLedgerData('10','By Aaron')"></a>

I don’t know why HTML replaces ‘By Arron’ with ‘By" ‘Arron’

>Solution :

It seems that you are not wrapping in quote marks in line 4, change to below to add that:

$html .= "<a onclick=\"" . $getLedgerData . "\"></a>";

Also you might need to change to single quotes this line also:

$getLedgerData = 'getLedgerData(\'' . $user_id. '\',\'' . $by . '\')';

Leave a Reply