William McCown
William McCown

Reputation: 1

PHP is inserting characters in the HTML that aren't in the echo string

php is adding ="" to the end of a string when I try to echo a button in the onclick property.

This gets sql data on an XAMPP server. It loops through and builds essentially a calendar showing all my bills and if I have paid them each month. I am using AJAX to update the database and change the paid value on a button click for each month.

I've tried various methods of using single and double quotes and escaping the quotes inside the string, but I still can't get it to output correctly.

echo $billName
foreach ($months as $v) {
//$clickstring = 'onclick="setCalendar("'.$billName.'","'.$v.'")';
$clickstring = "onclick=\"setCalendar(\"".$billName."\",\"".$v."\")";
if ($row["$v"] == "1") {
echo '<button class="paidBtn green-text"'.$clickstring . '><i class="fa fa-check" aria-hidden="true"></i></button>';
} else {
echo '<button class="unpaidBtn red-text"'.$clickstring.'><i class="fa fa-times" aria-hidden="true"></i></button>';
}

Say for instance on the first iteration $billname = "Amazon"; and $v = "jan". On the first echo Amazon is correct. However when it uses the same variable in the double click it inserts a space before it, and seems to perform a strtolower(). jan is inserted correctly, but it puts extra characters and quotation marks afterward. Here is the html output from the browser:

<button class="unpaidBtn red-text" onclick="setCalendar(" amazon","jan")=""><i class="fa fa-times" aria-hidden="true"></i></button>

Upvotes: 0

Views: 66

Answers (2)

William McCown
William McCown

Reputation: 1

I found the solution. I'm leaving the question up if in case anyone comes across the same problem. $clickstring = "onclick=\"setCalendar('".$billName."','".$v."')\"";

Upvotes: 0

Jason Byrne
Jason Byrne

Reputation: 1619

The problem is the html you are echoing out will look something like this

onclick="setCalendar("something", "month")"

Notice how you've got double-quote inside double-quote on that HTML attribute? You can't do that because it prematurely ends your onclick. You can get around this various ways like escaping it with a \ but that gets complicated because then your php you have to escape the \ which looks like \\ and that just gets crazy.

Just one possible way to rewrite this, using single quotes for the onclick arguments

echo $billName;

foreach ($months as $v) {
    $className = ($row[$v] == 1) ? 'paidBtn green-text' : 'unpaidBtn red-text';
    $icon = ($row[$v] == 1) ? 'check' : 'times';
    echo "<button class=\"$className\" onclick=\"setCalendar('$billName', '$v'\")>";
    echo "<i class=\"fa fa-$icon\" aria-hidden=\"true\"></i></button>";
}

I also refactored this a bit with ternaries and took out the if that had the html twice, which is a bit redundant IMO. And took out the string concatenation to make it a bit easier to read.

Upvotes: 1

Related Questions