views:

64

answers:

2

Hi,

How can i import javascript in php? No matter what i try, i can't seem to get the buttons in my page to trigger the events in javascript.

This is my javascript file content:

function addRow(tableID) {

 var table = document.getElementById(tableID);

 var rowCount = table.rows.length;
 var row = table.insertRow(rowCount);

 var colCount = table.rows[0].cells.length;

 for(var i=0; i<colCount; i++) {

  var newcell = row.insertCell(i);

  newcell.innerHTML = table.rows[0].cells[i].innerHTML;
  //alert(newcell.childNodes);
  switch(newcell.childNodes[0].type) {
   case "text":
     newcell.childNodes[0].value = "";
     break;
   case "checkbox":
     newcell.childNodes[0].checked = false;
     break;
   case "select-one":
     newcell.childNodes[0].selectedIndex = 0;
     break;
  }
 }
}

and

function deleteRow(tableID) {
 try {
 var table = document.getElementById(tableID);
 var rowCount = table.rows.length;

 for(var i=0; i<rowCount; i++) {
  var row = table.rows[i];
  var chkbox = row.cells[0].childNodes[0];
  if(null !== chkbox && true === chkbox.checked) {
   if(rowCount <= 1) {
    alert("Cannot delete all the rows.");
    break;
   }
   table.deleteRow(i);
   rowCount--;
   i--;
  }

 }
 }catch(e) {
  alert(e);
 }
}

This is how i try to import it in a php file:

       <HEAD>
 <script src="myfile.js" type="text/javascript"></script>
</HEAD>

what am i doing wrong?

A: 

make sure that your src attribute is pointing to the correct location of the JS file. (maybe it needs to be "/myfile.js" if the JS file is located under your document root, but the php file isn't).

ozk
I even tried passing the full path to the file, no luck.
Yustme
The "src" takes a URL, absolute or relative. How that maps onto the file system on your server is entirely determined by your webserver configuration: a full (file) path is almost certainly not going to work. You need to check whether the file is actually being loaded, as others have said, and if not, work out how you need to specify the src to satisfy your server's configuration. (It might also be a file permission issue on your server).
Colin Fine
+4  A: 

Open up the page in Firefox. Right click the page and select the option to show the sourcecode. Find the script tag and click the linked src. If it gives you a 404, the link is wrong. If it shows your JS code, it's fine. Install Firebug for Firefox and debug your code with it. Make sure your Event Listeners actually get triggered.

Gordon
Hi, i found it! it had to do with the path. i had to go back a few directories and then tell it where the js file is located some thing like this: ../../application/view/myfile.js
Yustme
@Yustme instead of a relative path, you can use an absolute path. Absolute Paths are relative to the Document Root. Try changing the path to `/application/view/myfile.js`. This should save you fiddling with directory traversal.
Gordon
+1 for nice step-by-step :)
chryss