access php in javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
monajain62
Forum Newbie
Posts: 1
Joined: Wed Jul 22, 2009 5:59 am

access php in javascript

Post by monajain62 »

Can anyone help me to access php variables in an external javascript file?

Thank You.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: access php in javascript

Post by jackpf »

I doubt that.

You could use cookies though.
DaiLaughing
Forum Commoner
Posts: 76
Joined: Thu Jul 16, 2009 8:03 am

Re: access php in javascript

Post 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?
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: access php in javascript

Post 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.
DaiLaughing
Forum Commoner
Posts: 76
Joined: Thu Jul 16, 2009 8:03 am

Re: access php in javascript

Post by DaiLaughing »

It was external javascript jackpf but I wonder if the variable could be passed to the function from the page.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: access php in javascript

Post 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.
Post Reply