0

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?

5 Answers 5

2

You should html encode it:

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

You could also use htmlspecialchars

Sign up to request clarification or add additional context in comments.

3 Comments

that produces &quot instead of " which actually breaks it
Errr no, &quot; is what you want and will fix it for you.
@Joshxtothe4, &quot; is converted to " by the browser before it reaches the Javascript parser.
1
echo "<a href='#' onclick='updateByQuery(\"Layer3\", \"" . json_encode($query) . "\");'>Link 1</a>";

This produces:

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

1 Comment

Not valid XHTML, but I won't -1 because he wants HTML it seems.
0

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

1 Comment

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?
0
echo "<a href='#' onclick='updateByQuery(\"Layer3\", " . json_encode($query) . ");'>Link 1</a>";

2 Comments

Fixed the formatting for you - you need to select it and hit the Code Sample (binary icon) button
@Roborg; this produces: <a href='#' onclick='updateByQuery("Layer3", Ed Hardy);'>Link 1</a> Notice there are no quotes around Ed Hardy.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.