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 :)
3 Answers 3
try not putting double quotes.
echo $xpos;
Comments
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,
$xposby itself is fine onclickshould 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.
1 Comment
dd is a form name you also should not use window.dd or dd-as-variable name. This will only work (sometimes) on IE. Use document.forms.dd.elements. Finally, for sanity's sake consider moving the multi-line handler function out into a <script> block or external script, assigning with link.onclick= function() { ... return false; }. href="#" is also less ugly than the javascript: pseudo-URL. (Always avoid javascript:.)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
$xposand$yposreturns.<a class="code" href="javascript:void(0);" onclick="javascript:if(window.dd && dd.elements) d.elements.name1.moveTo(<? echo "$xpos"; ?>, <? echo "$ypos"; ?>); return false;">