I have a javascript function that works fine when it is included in a <script></script> statement in the header of my php file, but when I move it to a separate .js file, it throws two errors.

The function is

function calculate()
{
  var i
  var optCount = <?php echo $opt_count ?>;
  var listItems = '<?php echo json_encode($lineItems); ?>';
   var listArray = JSON.parse(listItems);
    var itemQty = '';
    var itemPrice = '';
  var itemTot = '';
  var orderTot = '';
  var orderTotNum = 0;

  for(i=0; i<=optCount; i++){
     var qtyIndex = 'qty' + i;
    var qtyID = document.getElementById(qtyIndex).value;
   if (qtyID > 0){
      theQuantity = qtyID;
      qtyID =eval(theQuantity);
    } else {
      theQuantity = 0;
      qtyID = '';
    }
     var thePrice = listArray[i]["price"];

    var itemTot = theQuantity * thePrice;
     var totalIndex = 'total' + i;
     var elem = document.getElementById(totalIndex);
     if(itemTot > 0){
             elem.value = money(itemTot);
     }else {
     elem.value = '';
     }
     orderTotNum = orderTotNum + itemTot
     var gt = document.getElementById('grandtotal');
     if(orderTotNum > 0){
             gt.value = money(orderTotNum);
     }else {
          gt.value = '';
     }
  }
}

The errors received are

[Error] SyntaxError: Unexpected token '<' (OLRform.js, line 23)
[Error] ReferenceError: Can't find variable: calculate
    onchange (OLRform.php, line 139)

where line 23 is the line declaring the optCount variable. I tried to enclose it in quotes to make the number a string, but that didn't help.

What did I miss?

Line 5 contains PHP, and will not be parsed if it is in a js file.

Thanks. Then there is no way to pass PHP variables to a separate .js file? Does that mean that all my JavaScript must be in the header of the HTML?

The only way to do that is to tell apache to parse the .js file, or rename the file to .php

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.