Jump to content

Is it ok to embed php withing javascript (see below pls) ?


jd2007

Recommended Posts

function loadshopping()
  {
   <?php
   $theIP=$_SERVER['REMOTE_ADDR'];
   $_SESSION["ip"]=$theIP;?>
   document.write("Welcome, "+ <?php echo $_SESSION["ip"]; ?>);
   document.write("Quantity: "+ <?php echo "2"; ?>);
  }  

 

the above displays nothing but when i modify it to :

 

function loadshopping()
  {
   <?php
   $theIP=$_SERVER['REMOTE_ADDR'];
   $_SESSION["ip"]=$theIP;?>
   document.write("Welcome, "+ <?php echo "2"; ?>);
   document.write("Quantity: "+ <?php echo "2"; ?>);
  }  

 

it doesn't work if i echo a session variable...why...what can i do ?...pls help

If you are running Javascript client side, you cannot embed php code in it.

PHP runs server side only, if your Javascript writes PHP code to the window, the PHP module never sees it.

PHP run "behind the scenes", the only way to get code to the module is at the server.

Or you can use Javascript to write form and input elements, that then submit to a PHP script, which is stored on the server. Although this is only for transferring values from Javascript to PHP.

PHP can send Javascript code, because the browser accepts it the same way it accepts HTML.

Remember, the Javascript function your working with is called 'document', it is exactly that, the document in the browser, and the browser has no clue what to do with PHP code.

 

I hope all that rambling made some sense to you.

you have a syntax error, just remmeber the php on your javascript will be a string,

 

for example in this line

document.write("Welcome, "+ <?php echo $_SESSION["ip"]; ?>);

 

You need to include the echo inside the quote marks

document.write("Welcome,  <?php echo $_SESSION["ip"]; ?>");

 

So the HTML output will be something like this

document.write("Welcome, 123.345.667.23");

 

Let me know if this make sense.

I realized something. While you cannot technically embed PHP in Javascript, you can mix them. I was thinking of a case where Javascript creates dynamic php code.

My post applies to the Javascript runtime, not mixing php code and Javascript code in the same file on the server, as it appears is your case.

Appologies, I missunderstood you situation.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.