Page 1 of 1

access php in javascript

Posted: Wed Jul 22, 2009 6:05 am
by monajain62
Can anyone help me to access php variables in an external javascript file?

Thank You.

Re: access php in javascript

Posted: Wed Jul 22, 2009 6:06 am
by jackpf
I doubt that.

You could use cookies though.

Re: access php in javascript

Posted: Wed Jul 22, 2009 8:55 am
by DaiLaughing
You could place the variables in a hidden element on the html page. It would then be available to Javascript.

Can external Javascript files be written by PHP the way external CSS can?

Re: access php in javascript

Posted: Wed Jul 22, 2009 9:31 am
by jackpf
Yeah that's another point.

Although, why can't you just do this?

Code: Select all

 
echo '<script>
var something = \''.$a_php_var.'\'; //stupid highlighter...those should be escaped
</script>';
 
And yes, anything can be written in PHP as long as you send the right headers.

Re: access php in javascript

Posted: Wed Jul 22, 2009 9:40 am
by DaiLaughing
It was external javascript jackpf but I wonder if the variable could be passed to the function from the page.

Re: access php in javascript

Posted: Wed Jul 22, 2009 10:34 am
by jackpf
Well, if you put
var something = '<?php echo $var; ?>';
and then
<script src="yourscript.js"></script>
something should then be in the scope of yourscript.js as well...so should be able to access it.