Integrating PHP into JavaScript

Here's a little example that can throw you off for a while.

I have some JavaScript that upon clicking a button, the onClick fills a division using innerHTML. Let me just show you a bit.

<?php
$options = <<<eof
<option value="1">op 1</option>
<option value="2">op 2</option>
eof;

$javascript = <<<eof
<script type="text/javascript">
function on_click()
{
     document.getElementById('some_id').innerHTML = "<select name=\"somename\">{$options}</select>";
}
</script>
eof;
?>
<html><head><title>test</title>
{$javascript}
</head><body>
<input type="button" onClick="on_click()" value="click me" />
<div id="some_id"></div>
</body></html>

Basically, when you click that button, the division would be filled with an html <select> drop down box.

The code will not work.

Basically, in the $options variable, you must escape any quotations (") because, unlike php, the javascript doesn't auto escape them when putting a variable inside of another variable that contains quotes.

The 1st fix that needs to be done is,

$options = <<<eof
<option value=\"1\">op 1</option>
<option value=\"2\">op 2</option>
eof;

The second fix is that, even inside a heredoc, the javascript code must be in one line, so the final fix is.

$options = <<<eof
<option value=\"1\">op 1</option><option value=\"2\">op 2</option>
eof;

Page Comments (Click to edit)

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Powered by pmwiki-2.2.0-beta65