Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Undefined error in script 1

Status
Not open for further replies.

deeciple

Technical User
Mar 1, 2012
70
US
Hi All,

I am using the following in a repeating region table cell to return some values from my database:

Code:
<td><script>document.write(CnvToFrames("<?php echo $row_rstSegmentInfo['EOM']; ?>")-CnvToFrames("<?php echo $row_rstSegmentInfo['SOM']; ?>"));</script></td>

I am trying to sum these values up using the following script but I am getting an "undefined" error when I call the script.

JavaScript:
<script type="text/javascript">
var debugScript = true;

function sumTableColumn(tableId, colNumber) {
	// find the table with id attribute tableId
	// return the total of the numerical elements in column colNumber
	// skip the top row (headers) and bottom row (where the total will go)
	
	var result = 0;
	
	try 
	{
	 var tblElem = window.document.getElementById(tableId); 		   
	 var tblBody = tblElem.getElementsByTagName("tbody").item(0);
	 var i;
	 var totalRows = tblBody.rows.length;
	 for (i=1; i<(totalRows-1); i++) // skip first and last row (hence i=1, and totalRows-1)
	 {
		var currentRow = tblBody.rows[i];
		var currentCell = currentRow.cells[colNumber];			
		var curTextNode = currentCell.childNodes.item(0);
		if (debugScript)
		{
		   window.alert("text is " + curTextNode.data);
		} // end if
		
		// try to convert text to numeric
		var curNumber = parseFloat(curTextNode.data);
		// if you didn't get back the value NaN (i.e. not a number), add into result
		if (!isNaN(curNumber))
		   result += curNumber;

	 } // end for
	 
	} // end try
	catch (ex)
	{
	   window.alert("Exception in function sumTableColumn()\n" + ex);
	   result = 0;
	}
	finally
	{
	   return result;
	}

}
	
function writeResults()
{
	if (debugScript)
	   window.alert("Beginning of function writeResults");
	
	var sumSegTimesFrames = sumTableColumn("segments",6);

	try {
	  var totalSegmentTimeElem = window.document.getElementById("totalSegmentTime");
	  totalSegmentTimeElem.innerHTML = sumSegTimesFrames;
	}
	catch (ex)
	{
	  window.alert("Exception in function writeResults()\n" + ex);
	}
	return;
}
</script>

If I replace the table cell script with a number (say "123") the script works. How can I get it to work with the <td> <script>...</script></td>?

Thanks in advance for any assistance.

Ken
 
I am trying to sum these values up using the following script but I am getting an "undefined" error when I call the script.

What does the error say exactly, it should be telling you what is undefined?

What does the code look like after the PHP has been parsed, and the variables have been replaced? Javascript only sees the result of the PHP, so its better to look at the resultant html rather the PHP code.

Are the correct values being placed there?

What does you function, CnvToFrames(), do?






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi Vacunita,

It's the alert popup that is pointing to the var curTextNode being undefined:
JavaScript:
window.alert("text is " + curTextNode.data);

Vacunita said:
What does the code look like after the PHP has been parsed, and the variables have been replaced?
I'm not really sure how to find this out. When the page loads the correct values are being displayed in the table cells.

Vacunita said:
What does you function, CnvToFrames(), do?

The function takes some text formatted as 00:00:00:00 (hours:minutes:seconds:frames) and converts it to the equivalent value in frames. I have two functions that I use to perform calculations on video timecode:
JavaScript:
function CnvToTime(FrameCount)
{
var FRate = 29.97;
var TotalSecs = parseInt(FrameCount / FRate, 10);
var hours = parseInt(TotalSecs / 3600, 10);
var mins = parseInt((TotalSecs - hours * 3600) / 60, 10);
var secs = TotalSecs - hours * 3600 - mins * 60;
var frames = (FrameCount - TotalSecs * 30);
var dropframes = (hours * 108) + ((mins - parseInt(mins / 10, 10)) * 2);

if ((frames + dropframes) > 30) {secs =  secs + 1; frames = "1";}
else if ((frames + dropframes) == 30) {secs = secs + 1; frames = "0";}
else {frames = frames + dropframes;}

//FOR EACH LOOP TO FORMAT TIMECODE ARRAY
var i;
var timecode = Array();
timecode[0] = hours;
timecode[1] = mins;
timecode[2] = secs;
timecode[3] = frames

for (i=0;i<timecode.length;i++)
{if(timecode[i] < 10) timecode[i] = "0" + timecode[i];}

return timecode.join(':');
}

function CnvToFrames(timecode)
{
var FRate = 30;
var hours = parseInt(timecode.slice(0,2),10);
var mins = parseInt(timecode.slice(3,5),10);
var secs = parseInt(timecode.slice(6,8),10);
var frames = parseInt(timecode.slice(9,11),10);
var dropframes = (hours * 108) + (mins * 2) - (parseInt(timecode.slice(3,4),10) * 2);

var framecount = (hours * 3600 * FRate) + (mins * 60 * FRate) + (secs * FRate) + frames - dropframes;

return framecount;
}

Here is my table if it helps:

HTML:
<table id="segments" width="100%" border="0">
    <tbody>
      <tr>
        <th align="left" scope="col">&nbsp;</th>
        <th align="left" scope="col">Type:</th>
        <th align="left" scope="col">S.O.M.:</th>
        <th align="left" scope="col">E.O.M.:</th>
        <th align="left" scope="col">Dur.:</th>
        <th align="left" scope="col">Notes:</th>
      </tr>
      <?php do { ?>
        <tr>
          <td width="20"><?php echo $row_rstSegmentInfo['SegmentNumber']; ?></td>
          <td width="75"><?php echo $row_rstSegmentInfo['SegmentType']; ?></td>
          <td width="90"><?php echo $row_rstSegmentInfo['SOM']; ?></td>
          <td width="90"><?php echo $row_rstSegmentInfo['EOM']; ?></td>
          <td width="90"><script>document.write(CnvToTime(CnvToFrames("<?php echo $row_rstSegmentInfo['EOM']; ?>")-CnvToFrames("<?php echo $row_rstSegmentInfo['SOM']; ?>")));</script></td>
          <td><?php echo $row_rstSegmentInfo['SegmentNotes']; ?></td>
          <td><script>document.write(CnvToFrames("<?php echo $row_rstSegmentInfo['EOM']; ?>")-CnvToFrames("<?php echo $row_rstSegmentInfo['SOM']; ?>"));</script></td>
        </tr>
        <?php } while ($row_rstSegmentInfo = mysql_fetch_assoc($rstSegmentInfo)); ?>
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td>Total Segment Time</td>
          <td id="totalSegmentTime"></td>
        </tr>          
    </tbody>
</table>

Thanks,

Ken
 
I'm not really sure how to find this out. When the page loads the correct values are being displayed in the table cells.
Just open the page source in the browser->view->Source. You'll see no PHP, only the html produced by it.

Anyway, based on this:

Code:
 var tblElem = window.document.getElementById(tableId); 		   
	 var tblBody = tblElem.getElementsByTagName("tbody").item(0);
	 var i;
	 var totalRows = tblBody.rows.length;
	 for (i=1; i<(totalRows-1); i++) // skip first and last row (hence i=1, and totalRows-1)
	 {
		var currentRow = tblBody.rows[i];
		var currentCell = currentRow.cells[colNumber];			
		var curTextNode = currentCell.childNodes.item(0);
		if (debugScript)
		{
		   window.alert("text is " + curTextNode.data);
		} // end if

if curTextNode is undefined, it means currentCell.childNodes.item(0); is not returning a valid object

If you alert currentCell.childNodes.length what does it return?

If that returns a valid value such as 1 or 2, then we know currentCell has children. If it returns 0 then that means the currentCell is empty.
If currentCell is empty then we'd need to look at what is defining currentCell:

Code:
var currentCell = currentRow.cells[colNumber];

We'd need to be sure that colNumber points to a column that actually has cells with children.








----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I looked at the source and it is showing the script with the text that is being echoed from PHP. Here is an example:

HTML:
<td width="90"><script>document.write(CnvToTime(CnvToFrames("02:50:18:20")-CnvToFrames("02:50:16:00")));</script></td>

Vacunita said:
If you alert currentCell.childNodes.length what does it return?

The alert returns 2.

Vacunita said:
var currentCell = currentRow.cells[colNumber];
We'd need to be sure that colNumber points to a column that actually has cells with children.

When I replace the script in the table cell with an actual number, the function works and the correct column (the one that I replaced with a number in it's cells) is summed.

Thanks for sticking with me on this.

Ken

 
It could be the value being produced by PHP is treated as text. Perhaps running it through the parseInt function would help.

Code:
colNumber = parseInt(colNumber);



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I will try that but why would running the parameter colNumber through the parseint function affect the way that the PHP value in the <td> is treated?
 
It doesn't. but it does affect how the value is perceived by JS. If JS is reading it as a string and not a number, it may not be able to correctly use it to determine the cell you are looking for. Hence the cell is undefined.

Making it an actual number by using the parseInt, will make JS perceive it as a integer, and be able to correctly use it.

If do this deliberately for instance:
Code:
colNumber = " 4";
var currentCell = currentRow.cells[colNumber];
alert(currentCell.childNodes);

Notice the space before the "4". I'm going to get the undefined error on currentCell because the string "_4" cannot be used to find an actual column.

With that said, looking into your table structure, you do have some empty td's there which could be causing the error, as they have no contents, so no childs, hence an undefined curTextNode when it gets to them.

You need to understand what the code is doing and what it expects so it can move on. Look at what the document.write is actually outputting to the table cell. Is it a valid number does it have a space? Also why is the length of currentCell returning 2, is there more than one piece of text there? some additional tag?

Could we possibly see, what the source code looks like once the page is rendered, and all PHP has been parsed, but before you initate your sum function. This would give me a good idea of what the sum function is actually seeing.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi Vacunita,

I got it sorted out. It required a rethinking of the table and the calculations are ALL being handled in the script now. Once I got a handle on what the code was doing and where it was failing I was able to fix it and add some additional calculations that I needed. Here is the working code. Thanks again for your help!

Ken

JavaScript:
var debugScript = true;

function sumTableColumn(tableId) {
	// find the table with id attribute tableId
	// return the total of the numerical elements in column colNumber
	// skip the top row (headers) and bottom row (where the total will go)
	var result = 0;

	try {
	 var tblElem = window.document.getElementById(tableId); 		   
	 var tblBody = tblElem.getElementsByTagName("tbody").item(0);
	 var i;
	 var totalRows = tblBody.rows.length;

   var firstSOM = tblBody.rows[1].cells[2].innerHTML;
   var lastEOM = tblBody.rows[totalRows-3].cells[3].innerHTML;
   var TRT = CnvToTime(CnvToFrames(lastEOM)-CnvToFrames(firstSOM));
   var trtCell = document.getElementById("totalRunTime");
   trtCell.innerHTML = TRT;

  	for (i=1; i<(totalRows-2); i++) { // skip first and last row (hence i=1, and totalRows-1)
  	 
  		var currentRow = tblBody.rows[i];
      var somCell = currentRow.cells[2].innerHTML;
      var eomCell = currentRow.cells[3].innerHTML;
  		var durCell = currentRow.cells[4];
      durCell.innerHTML = CnvToTime(CnvToFrames(eomCell)-CnvToFrames(somCell));
  		var durFrames = CnvToFrames(durCell.innerHTML);

  		if (debugScript) {
  		   window.alert("text is " + durFrames);
  		} // end if
  		
  		// try to convert text to numeric
  		var curNumber = parseFloat(durFrames);
  		// if you didn't get back the value NaN (i.e. not a number), add into result

  		if (!isNaN(curNumber))
  		   result += curNumber;
  	} // end for
	} // end try

	catch (ex) {
	   window.alert("Exception in function sumTableColumn()\n" + ex);
	   result = 0;
	}

	finally {
	   return result;
	}
}
	
function writeResults() {
	if (debugScript) {
	   window.alert("Beginning of function writeResults");
	}

	var sumSegTimesFrames = CnvToTime(sumTableColumn("segments"));
  alert(sumSegTimesFrames);

	try {
	  var totalSegmentTimeElem = window.document.getElementById("totalSegmentTime");
	  totalSegmentTimeElem.innerHTML =  sumSegTimesFrames;
	}
	catch (ex) {
	  window.alert("Exception in function writeResults()\n" + ex);
	}

	return;
}
 
Glad you got it sorted out.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top