Jump to content

Send PHP to JavaScript


iyeru42

Recommended Posts

I was wondering how one would send PHP stuff into JavaScript. For example, make a javaScript variable act under a PHP class, or sending PHP variables to a javaScript variable.

Link to comment
Share on other sites

In ASP.NET (C#) I would do something like this to get a C# variable into my java script:

<script type="text/javascript">var userid = <%= UserID %>;</script>

I'm guessing, in PHP, it'd be something like this:

<script type="text/javascript">var userid = <?php echo $UserID; ?>;</script>

Link to comment
Share on other sites

People seem to have problems with this type of stuff, I think you might be confused with how PHP works. PHP is a language that generally displays text. That is the output of a PHP program, and other data like images, PDF, whatever. But generally all you are working with is text, most often the text is in the format of HTML or XHTML code. Now you want to write out Javascript code, why is that any different? If you want to write this function in java script:

function validate(val){  if (val != "some value")	alert("wrong");}

If you want to replace values or whatever in that piece of text, which happens to be formatted as Javascript code, how is that any different then inserting values from PHP into HTML? If you want to insert PHP variables into the text, you do it exactly the way you do with anything else.

function validate(val){  if (val != "<?php echo $some_value; ?>")	alert("<?php echo $wrong_message; ?>");}

You just have to keep in mind that all you are doing is writing text, this is not code! It's text. It just so happens that a web browser will see this text and execute it as code, but that doesn't have anything to do with PHP. As far as PHP is concerned, you are writing text to some output device, in this case the response of a web server. There is no connection between PHP and Javascript the same way there is no connection between PHP and HTML, but you can use one to write out the other.

Link to comment
Share on other sites

no these are all valid javascript

if(some condition)  alert("do somethign here)for(looping)  alert("do somethign here)while(condition)  alert("do something here")if(condition)  if(another condition)	if(yet another condition)	  alert("do something here")//etc,etc,etc

Link to comment
Share on other sites

Thanks. BTW justsomeguy, your IF statement needs the curly brackets, unless you put it on one line.
What do you mean, it is on one line. We covered the syntax of IF statements in CSE 101 during the Fall of 98, since then I seem to have a pretty good handle on it.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...