PHP code inside JavaScript

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

PHP code inside JavaScript

Post by aceconcepts »

Hi

How can I include some PHP code inside a JavaScript?

This is what I want to do:

Code: Select all

 
<script type="text/javascript">
  function dateChanged(calendar) {  
    if (calendar.dateClicked) {
      var y = calendar.date.getFullYear();
      var m = calendar.date.getMonth();     // integer, 0..11
      var d = calendar.date.getDate();      // integer, 1..31
      
      window.location = "/and/index.php?page=appointments&action=diary&d="+d+"&m="+m+"&y="+y;
    }
    
  };
 
  Calendar.setup(
    {
 
          //THIS IS WHERE I WANT TO INCLUDE THE PHP CODE - SEE BELOW
 
      date         : $_REQUEST['d']."/".$_REQUEST['m']."/".$_REQUEST['m'],
 
      flat         : "calendar-container", // ID of the parent element
 
          flatCallback : dateChanged           // our callback function
    }
 
  );
</script>
 
the above JavaScript is held in a '.php' file.

Any ideas how this can be done?

Thanks
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: PHP code inside JavaScript

Post by Chris Corbyn »

That will work fine if it was directly embedded into the page.

If you need a separate file, put this at the top of it.

Code: Select all

<?php header("Content-Type: text/javascript"); ?>
Then when you include it in the page:

Code: Select all

<script type="text/javascript" src="your-php-file.php"></script>
Post Reply