tags:

views:

107

answers:

5

Hello,

I have this PHP code

echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . json_encode($query) . ');">Link 1</a>';

which generates a link like this:

<a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");">Link 1</a><li>Link 2</li>

Causing the javascript to not be called. How would I make it generate single quotes around the result of $query, in this case ed hardy?

A: 

Try to do the reverse... use single quotes for html, and double quotes for javascript. That's how we do that in fact.

tpk
I am unsure how to modify the echo line to sue both, as I must have double quotes around the JavaScript function. Do I just escape them?
Joshxtothe4
A: 
echo "<a href='#' onclick='updateByQuery(\"Layer3\", " . json_encode($query) . ");'>Link 1</a>";
Fixed the formatting for you - you need to select it and hit the Code Sample (binary icon) button
Greg
@Roborg; this produces:<a href='#' onclick='updateByQuery("Layer3", Ed Hardy);'>Link 1</a>Notice there are no quotes around Ed Hardy.
cLFlaVA
+2  A: 

You should html encode it:

echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . htmlentities(json_encode($query)) . ');">Link 1</a>';

You could also use htmlspecialchars

Greg
Joshxtothe4
Errr no, " is what you want and will fix it for you.
Greg
@Joshxtothe4, " is converted to " by the browser before it reaches the Javascript parser.
strager
+1  A: 
echo "<a href='#' onclick='updateByQuery(\"Layer3\", \"" . json_encode($query) . "\");'>Link 1</a>";

This produces:

<a href='#' onclick='updateByQuery("Layer3", "Ed Hardy");'>Link 1</a>
cLFlaVA
Not valid XHTML, but I won't -1 because he wants HTML it seems.
strager
A: 

Quotes are a problem with inline handlers. As RoBerg says, you need to use htmlentities in the text.

Another way around it is to use hook methods and anonymous functions, rather than inline handlers.

echo '
<a href="#" id="link_1">Link 1</a>
<script>document.getElementById("link_1").onclick =
       function() { updateByQuery("Layer3", '.json_encode($query).'); }
</script>
';
staticsan