Joshxtothe4
Joshxtothe4

Reputation: 4211

php quoting problem

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?

Upvotes: 0

Views: 155

Answers (5)

staticsan
staticsan

Reputation: 30575

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>
';

Upvotes: 0

cLFlaVA
cLFlaVA

Reputation: 1498

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

This produces:

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

Upvotes: 1

theman_on_vista
theman_on_vista

Reputation:

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

Upvotes: 0

Greg
Greg

Reputation: 321864

You should html encode it:

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

You could also use htmlspecialchars

Upvotes: 2

tpk
tpk

Reputation: 2131

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

Upvotes: 0

Related Questions