To print a variable into Javascript you just add curly braces (this only works when you are emitting a double quoted string, so:
echo "<td><a href='#' onclick='disp_confirm({$row->university})'>Delete</a></td>";
will work and
echo '<td><a href="#" onclick="disp_confirm({$row->university})">Delete</a></td>';
will not work. The same for {$variables}
, {$array['of values']}
etc.
(In the above code, $row->university
has to be an integer, or you'll get a Javascript error. If so, quote the value with escaped single quote marks)
UPDATE (thanks to Mihai Iorga): you must take into account how the variable will interact with the Javascript code. It is not enough to quote strings, because the variable might itself contain a quote mark. So if your university was "Shi'Kahr University", the HTML would become
onclick='disp_confirm(\'Shi'Kahr University\')'
and the Javascript would be immediately broken. So you also have to use addslashes()
to ensure that your string is properly quoted. Since you are writing a string inside a string, you need to call addslashes()
twice, to get
onclick='disp_confirm(\'Shi\\\'Kahr University\')'
To pass a Javascript value to PHP script on server side, you can use AJAX (e.g. jQuery library) or you can add the value to the URL and reload the page:
alert("Submitting " + value);
location.href = '?variable=' + value;
The script will execute again from the beginning (which may or may not be what you want), and $_GET['variable']
will then contain value. You can distinguish the two cases with an if
:
<?php
if (isset($_GET['variable']))
{
// This is the second round
}
else
{
// This is the first time
}
// common code goes here
?>
Finally, there are libraries that allow mixing PHP and Javascript. They basically work as above, but they take care of the heavy lifting, variable passing, escaping, and calling back. See for example XAJAX, but several others exist.