Home > Net >  PHP file is not reading my js script file
PHP file is not reading my js script file

Time:05-14

I am trying to make sure my php file is reading my js file and when I click my decrease button, my console says

Uncaught ReferenceError: decrease is not defined
onclick http://localhost:3000/index.php:1

I know this is indicating that my decrease() function does not exist when I click the button which is not true. I made sure that I included the html script tag as well.

Here are both of my files

index.php

  <?php
  $price = 3;
  $quantity = 5;
  $total = $price * $quantity
?>

<!DOCTYPE html>
<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <p>Total: <?php echo $total; ?> </p>
    <button onclick='decrease();'>Click Me</button>
    <input type='text' id = 'num' value="0"></input>
    
    <script type='text/javascript' src='./index.js'></script>
  </body>
</html>

index.js

let i = null;

 
  function decrease(){
    i = i - 1;
    document.getElementById('num').value = i;
    console.log(i)
  }

I've tried to restart my webserver a few times and it did not work. What am I missing that its preventing it from seeing the function in my external js script file?

CodePudding user response:

From my understanding when working with a webserver, I do not use relative paths for my resources like js, CSS or images.

If your directory looks like this:

Main
 |- index.php
 |- index.js

Then you can import your javascript file like so without the dot .:

<script type='text/javascript' src='/index.js'></script>

Sometimes when you create the project from Apache Netbean, the project URL will become http://localhost/ProjectName

For example, if you access your index.php from http://localhost/ProjectName/index.php, then you should be able to get the javascript file like so:

<script type='text/javascript' src='/ProjectName/index.js'></script>

I have not tested it yet, hope it helps.

  • Related