tags:

views:

80

answers:

3

Hello every1!

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 :)

A: 

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

DeveloperChris
Just to enhance the above answer you can also use the syntax <?=$xpos ?> to print out the xpos but scope still matters and it won't work in some installations (due to a php.ini setting) So I personally don't recommend this method
DeveloperChris
+1  A: 

try not putting double quotes.

echo $xpos;
junmats
wow thank you so much, i've been messing around with this for ages, it works!!!!
Pete Herbert Penito
no prob. you can at least accept my answer.hehe
junmats
+1  A: 

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.

K Prime
Assuming `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:`.)
bobince