3

How can I include a javascript file using php echo ?

I am creating a html page using php ---

echo "<html><head><link rel='stylesheet' type='text/css' <script src="Calculation.js"> </script>  href='style.css' </head><body>";

I have included script code in the above line and then in form tag ---

<form action='/workdonecalculation/index.php?_pagination_off=1' method='post'  class='form'  onSubmit='return workdone();'>

But my php code doesn't call my javascript file (Calculation.js)

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
Sun
  • 89
  • 1
  • 2
  • 11

6 Answers6

5
 echo "<html><head><link rel='stylesheet' type='text/css'/> <script src='Calculation.js'></script>"

First close link tag, and you are using double quotes.. for the src= use single, because you are already using double in the echo "". So src='Calculation.js'

Also you can do this the easy way use variables.

$a=<<<HERE
<script src="Calculation.js"> </script>
HERE;
echo $a;

Also you can close php and start html where ever you wish

<?php
if($i)
{
?>
<script src=""></script> 
<?php
}
?>

Is that what you wanted???

geekman
  • 2,224
  • 13
  • 17
  • No, I din't close the link tag "/>" and that was the problem. Thank you for helping me ! – Sun Oct 05 '12 at 11:34
3

You didn't close <link> tag and <script> tag misplaced inside <link> tag. Also you need to escape the double quotes in src="Calculation.js" or simple you enclose with single quotes.

Here is the correct code,

echo "<html><head><link rel='stylesheet' type='text/css' href='style.css' /><script src='Calculation.js'></script> </head><body>";
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
1

You'll need to complete link tag first.

Try this

echo "<html><head><link rel='stylesheet' type='text/css' href='style.css' /> <script src='Calculation.js'></script>  </head><body>";
Mohit Mehta
  • 1,283
  • 12
  • 21
1

Seems the link tag is not closed properly and the double quotes in script tag is not escaped.

Try the below code :

echo "<html><head><link rel='stylesheet' type='text/css' href='style.css'><script src='Calculation.js'></script></head></html>";
Merlin
  • 81
  • 5
1

use single qoute:

echo '<html><head><link rel="stylesheet" href="style.css" type="text/css" /> <script type="text/javascript" src="script.js"></script> </head><body>';

hope it helps

Nwafor
  • 184
  • 6
1
print("<script type=\"text/javascript\" src=\"Calculation.js\"></script>");

Are you running this code on Windows, if not are you sure the file is called "Calculation.js" and not "calculation.js"? Also, is it definitely in the same directly as the PHP script that's calling it?

EM-Creations
  • 4,195
  • 4
  • 40
  • 56