I'm attempting to put a php variable inside a javascript function and having no luck, here's what I got
<a class="code" href="javascript:void(0);"
onclick="javascript:if(window.dd && dd.elements)
d.elements.name1.moveTo(<? echo "$xpos"; ?>, <? echo "$ypos"; ?>);
return false;">
name1.moveTo(name1.x-20, name1.y+7);</a>
`
the moveTo() function works perfectly when I send it a javascript variable or simple numbers.
the reason its in a php variable at all is because I need the xpos to be inside a session variable to be accessed in other places. Afterwards I assign it as follows
$_SESSION['productcheck']['x'] = $xpos;
I'm kinda new to this, if you haven't already noticed, Thank you ahead of time :)
try not putting double quotes.
echo $xpos;
This is just to clarify, but you seem to have a typo (d should be dd). Corrected:
<a class="code" href="javascript:void(0);"
onclick="return (function () {
if(window.dd && dd.elements)
dd.elements.name1.moveTo(<? echo $xpos; ?>, <? echo $ypos; ?>);
return false;
})()"
>
name1.moveTo(name1.x-20, name1.y+7);
</a>
Some issues:
You don't need PHP variable interrpolation, $xpos by itself is fine
onclick should have only one expression that returns false, so you'd ideally wrap it in a function elsewhere. Here I used an anonymous one
Also, onclick need not start with 'javascript:, since it already is implicitly so.
My guess would that xpos and ypos are not in scope at the time that part of the page is processed.
Scope refers to the enclosing braces. for example the following will not work
$xpos = 100;
function printx(){
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
Nothing will be printed
to fix it use the following
$xpos = 100;
function printx(){
global $xpos;
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
this would then print 100
Related
Is there any possible way to have four levels of quotes? Or a more efficient way to print javascript using PHP?
Here is the context for why I need four levels of quotes:
The first level is required to wrap around script to echo.
<?php echo '<script></script>';
The second level is required to wrap around html to print in java
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button>test</button>\'</script>';
The third level is to wrap around onclick function in button
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function()">test</button>\'</script>';
The fourth level is to wrap around the parameters in the function
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function(*insert quote*parameter*insert quote*)">test</button>\'</script>';
Edit 1:
The entire script needs to be in echoed by php because in some scenarios the entire scripts needs to exist and other scenarios it needs to not exist e.g.
<?php if($variable == "do_not_print"){// do nothing}else{//echo script}
You can avoid string quoting problems by dropping out of the PHP context entirely and using
<?= ... ?>
to insert server-side values into the output.
json_encode() also helps sanitise values for safe use in a JavaScript context.
I also recommend using the DOM library for creating and inserting elements
For example
if ($someThingOrOther) :
// end PHP context
?>
<script>
(() => { // IIFE to avoid polluting the global scope
const someValueFromPhp = <?= json_encode($someValue) ?>
const button = document.createElement('button')
button.textContent = 'test'
button.addEventListener('click', () => {
some_function(someValueFromPhp)
}, false)
const box = document.getElementById('box')
// empty out "box", faster than using "innerHTML"
while(box.firstChild) {
box.removeChild(box.firstChild)
}
box.appendChild(button)
})()
</script>
<?php
// and now back to PHP
else:
?>
<script>
// ...
</script>
<?php
endif;
quote 1: ''
quote 2: ""
quote 3: \'\'
quote 4: \"\"
like this:
<div id="root"></div>
<?php
echo '<script type="text/javascript">
document.getElementById("root").innerHTML = "<button onclick=\"alert(\'its work\')\">test</button>\n";
</script>';
?>
The JS function is
function func(arg){
alert(arg);
}
When I do
echo "<div onclick=\"func($arg)\">Text</div>";
in php, it doesnt work
but when I do
echo "<div onclick=\"func()\">Text</div>";
it works and an alert with undefined text pops up.
How do I pass argument?
You need to quote the arguments. e.g.
<?php
$foo = 'bar';
?>
echo "function($foo) { ... }";
is going to produce the code
function(bar) { ... }
where bar will be interpreted as an undefined variable.
Safest method is to output your PHP variables via json_encode(), to guarantee you're producing syntactically valid javascript. e.g.
echo 'function(' . json_encode($foo) . ') { ... }';
which would produce (in this case)
function ('bar') { ... }
You need to wrap $arg in quotes. Example:
echo "<div onclick=\"func('$arg')\">Text</div>";
(using single quotes around arg as you're using double quotes for the string)
You can do like this (if $args exists of course)
echo '<div onclick="func('.$arg.')">Text</div>';
I'm sending data to function by onclick event but I can't get string value I just getting integer value, it say that 'value' is not defined. what is the problem.
My code is:
<a href="javascript:void(0)"
onclick="begin(<?php echo $data['user_id'];?>,
<?php echo $data['name'];?>);">
This is my function:
function begin(id,name)
{
alert(id);
alert(name);
}
I'm not getting name value, if I pass hard-code string then its also not getting here only integer are accessible.
You need to wrap your parameters in quotes to make it a string.
<a href="javascript:void(0)" onclick="begin('<?php echo $data['user_id'];?>','<?php echo $data['name'];?>');">
As Matt says, without quotes it won't be recognised.
That said, I don't think his answer is correct. I would prefer this code: (whitespace added for legibility)
<a href="javascript:void(0);" onclick="begin(
<?php echo htmlspecialchars(json_encode($data['user_id'])); ?>,
<?php echo htmlspecialchars(json_encode($data['name'])); ?>
);">
json_encode (docs) is good for passing any PHP variable (except Resources) into JavaScript. In this case, it will add quotes around the string, and escape characters as needed with backslashes. Since it's going in an attribute, you need htmlspecialchars to convert symbols to be safely insertable.
i'm having some trouble using javasript in php code, I'm confused in using double quotes and single quotes.
echo 'Delete';
or how to do the above code in php ?.
Thanks
use this code
echo 'Delete';
you have to escape the quotes.
http://viper-7.com/F6uI0L
You need to escape the quotes with htmlspecialchars (for HTML):
echo '<a href="..." onclick="return confirm('
.htmlspecialchars('"Are you sure"') . '">Delete</a>';
(alternatively you could just write ")
...but don't do that. Use JS event registration:
document.getElementById('a-id').addEventListener('click', function (e) {
if (!confirm("Are you sure...")) {
e.preventDefault();
}
});
Do that in JS file. It requires that the <a> have an ID (you could also do it with a host of other selectors, but ID is the simplest).
Change like following
echo "Delete";
Why don't you put the HTML outside of PHP tags? For example you could do:
...
?>
Delete
<?php
...
Another way to echo HTML is:
echo <<<HTML
Delete
HTML
Error in confirm("Are you sure you want to delete?")"> you need to escape double quote.
You need to call the javascript function using php echo
echo 'href_link';
...but you have to use JS function
<html><head><script type="text/javascript">
function fun()
{
if(confirm('are you sure')) return TRUE;
else return FALSE;
}
</script>
</head>
<body></body>
</html>
i want to pass a variable through to a php on an onClick event, it doesn't seem to be passing it through to the page properly though.
Here's my html
<a href="data.php" onClick="video(We Have a Pope)" hidefocus="">
and the relevant javascript function
function video(result) {
$('#information').load('data.php?result=' + result);
document
}
My php page looks like this
<?php
$result = $_GET['result'];
echo $result;
?>
Nothing is being outputted though :S
onClick="video(We Have a Pope)" should be onClick="video('We Have a Pope')"
You need quotation marks when you pass string as parameter, like this:
<a href="data.php" onClick="video('We Have a Pope')" hidefocus="">
<a href="data.php" onClick="javascript:video('We Have a Pope');" hidefocus="">
onClick="video('We Have a Pope');"
or
onClick="video(\"We Have a Pope\");"