Reputation: 6789
I am grabbing a string from a "title"
field and passing it to an addText
javascript function.
I am having trouble passing the string properly though. This--->
while ($row = mysql_fetch_assoc($part_result)){
echo "<div id ='link' onclick = 'addText("$row['title']");'>" . $row['title'] ."</div>";
}
yields a syntax error.
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';'
Thanks for your help!
Upvotes: 0
Views: 116
Reputation: 19550
You error is coming from the fact that you're not properly concatenating your static strings to your variables in all places.
echo "<div id ='link' onclick = 'addText("$row['title']");'>" . $row['title'] ."</div>";
Should be
echo '<div id="link" onclick="addText( \'' . $row['title'] . '\' );">' . $row['title'] . '</div>';
Also, since $row['title']
is being used inside of an HTML attr, it should be entitized to avoid quote collisions:
echo '<div id="link" onclick="addText( \'' .htmlentities( $row['title'], ENT_QUOTES ) . '\' );">' . $row['title'] . '</div>';
And for the cleanest code I'd use printf()
:
printf( '<div id="link" onclick="addText( \'%s\' );">%s</div>', htmlentities( $row['title'], ENT_QUOTES ), $row['title'] );
Upvotes: 2
Reputation: 760
Use json_encode
to pass your title through. This will encode it just in case you have single or double quotes (or any other bad character) in it.
Also your error is coming from the variable itself. Since your are using double quotes, wrap your variable with curly brackets:
addText('{$row['title']}');
Upvotes: 0
Reputation: 3754
Try this :
echo '<div id="link" onclick="addText(\''.$row['title'].'\')">'.$row['title'].'</div>';
You don't need the ;
after addText()
Upvotes: 0
Reputation: 47619
echo "<div id ='link' onclick = 'addText(\"".$row['title']."\");'>" . $row['title'] ."</div>";
Upvotes: 4