Forum Moderators: open

Message Too Old, No Replies

Can't get element by id

         

andrewsmd

9:56 pm on Feb 18, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What is wrong with this code
<div id="outputlink"></div>

function outputNextLink(data){
document.getElementById("outputlink").innerHTML = data;
}//outputnextLink

When I run outputNextLink("somedata"); I get nothing. My console says Uncaught TypeError: Cannot set property 'innerHTML' of null
which means it's not getting the element. I just can't figure out why? My JS comes after the html is generated

LifeinAsia

10:07 pm on Feb 18, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



It worked fine when I tried it.

Can you post the code where you are "running" outputNextLink("somedata"); on your page?

andrewsmd

10:16 pm on Feb 18, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sure here is the whole file. It may get a little hairy though. I have have php mixed in with this too.


<?php
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">

.tablePadding{
padding-right: 20px;
}

</style>
<?php

//require our connection
require_once("connection.php");
if(isset($_GET['q'])){

$_SESSION['typedText'] = $_GET['q'];

}//if
if(!(isset($_SESSION['dropValue']))){

$sessionQuery = "select * from input limit 1;";
$result = mysql_query($sessionQuery) or die("Couldn't execute query");
//set the session var
while ($row= mysql_fetch_array($result)) {
$_SESSION['dropValue'] = $row['Radio'];

}//while
}//else

?>
<title>Search</title>
<meta name="author" content="Steve R, [designplace.org...]

</head>

<body>

<form name="form" method="get" id="frmMain">
<img src="http://www.amateurradiobluebook.com/RadioPics/BannerTop2.jpg">
<div align="center">
<br /><br />
<select id="select" name="searchDropDown" onchange="callReturnData('drop');">
<?php

// get results
$query .= "select * from input;";
$result = mysql_query($query) or die("Couldn't execute query");
//populate the dropdown
while ($row= mysql_fetch_array($result)) {


if($_SESSION['dropValue'] == $row['Radio']){
echo("<option value=\"{$row['Radio']}\" selected=\"selected\">{$row['Radio']}</option>\n");
}//if
else{
echo("<option value=\"{$row['Radio']}\">{$row['Radio']}</option>\n");
}//else

}//while
?>
</select> <input type="button" value="Search" name="dropSearch" onclick="callReturnData('drop');" />
&nbsp;&nbsp;<span id="ebaySearch"></span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="text" name="q" id="inputText" value="<?php echo($_SESSION['typedText']); ?>" />
<input type="button" name="Submit" value="Search" onclick="callReturnData('text');" />
<br>

</div>
<div id=\"outputLink\"></div>
</form>
<div id="outputDiv">

<?php

if($_GET['next'] != ""){
$_SESSION['typedText'] = $_GET['q'];
returnData($_GET['next']);
}//if
elseif($_GET['q'] != ""){
$_SESSION['typedText'] = $_GET['q'];
returnData($_GET['q']);

}//elseif
/*
else{
//if they click the search from the
//text box
if(isset($_GET['Submit'])){

}//if isset submit

//they clicked the search from the dropdown
elseif(isset($_GET['dropSearch'])){

returnData($_GET['searchDropDown']);

}//elseif
}//else
*/
//this function returns the data based on the input either
//from the dropdown or the text box
function returnData($inputFromUser){

// Get the search variable from URL

$var = $inputFromUser;
$trimmed = trim($var); //trim whitespace from the stored variable

// rows to return
$limit=20;

// Build SQL Query
$query = "select * from CleanDataCombined2010 where Keyword='$trimmed'
order by Price"; // EDIT HERE and specify your table and field names for the SQL query

$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);

// Retrieve s from URL
if($_GET['s']){

$s = $_GET['s'];
}//if get s
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: &quot;" . $trimmed . "&quot; returned zero results</p>";

// google
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the
search on google</p>";
}
else{
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}


// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");

// display what the person searched for
echo "<p>You searched for: &quot;" . $var . "&quot;</p>";

// begin to show results set
echo "<p align=&#34;center&#34>Results are listed below. Please note that these are sold items and eBay only keeps a record of them for 90 days or less. Links may be expired.</p>";

//check to see if the averages exist in the database
if(mysql_num_rows((mysql_query("SELECT * FROM averages WHERE `desc` = '{$inputFromUser}'")))){

$resultT = mysql_query("SELECT * FROM averages WHERE `desc` = '{$inputFromUser}'") or die("Couldn't execute query");
while($avgRow = mysql_fetch_array($resultT)){
$avg20 = $avgRow['average20'];
$avg40 = $avgRow['average40'];
$avg60 = $avgRow['average60'];
$avg80 = $avgRow['average80'];
$avg100 = $avgRow['average100'];
}//while
}//if

//else we do the calcuation to get the percentile
else{


//now we do the averages for the percentile.
set_time_limit(300);
$amountArray = array();
$percentileArray = array();
$queryAvg = "select * from CleanDataCombined2010 where Keyword='$trimmed'
order by Price";
$resultAvg = mysql_query($queryAvg);

//insert the prices into an array
while($rowAvg= mysql_fetch_array($resultAvg)) {

array_push($amountArray, "{$rowAvg['Price']}");

}//while

//an array of the percentiles
$percentileArray = array();

//now we find the percentile of each price
foreach($amountArray as $i){

array_push($percentileArray, calculatePercentile($amountArray, $i).",{$i}");

}//foreach

//now go through the array and find what section the percentile goes in
$per20Array = array();
$per40Array = array();
$per60Array = array();
$per80Array = array();
$per100Array = array();

foreach($percentileArray as $i){

$split = split(",", $i);
$tempPer = $split[0];
$tempPrice = $split[1];

if($tempPer <= 20){

array_push($per20Array, $tempPrice);

}//if
elseif($tempPer > 20 && $tempPer <= 40){

array_push($per40Array, $tempPrice);

}//elseif
elseif($tempPer > 40 && $tempPer <= 60){

array_push($per60Array, $tempPrice);

}//elseif
elseif($tempPer > 60 && $tempPer <= 80){

array_push($per80Array, $tempPrice);

}//elseif
elseif($tempPer > 80 && $tempPer <= 100){

array_push($per100Array, $tempPrice);

}//elseif
else{

echo("can't find number $tempPrice");

}//elseif

}//foreach percentileArray

//now calculate the averages

$avg20 = findAverage($per20Array);
$avg40 = findAverage($per40Array);
$avg60 = findAverage($per60Array);
$avg80 = findAverage($per80Array);
$avg100 = findAverage($per100Array);
}//else

echo("<table>
<tr><td class='tablePadding'>Parts</td>
<td class='tablePadding'>Fixer</td>
<td class='tablePadding'>Average</td>
<td class='tablePadding'>Excellent</td>
<td class='tablePadding'>Like New</td>
<td><span id=\"averageOutput\"></span></td></tr>
<tr><td><input type=\"text\" size=10 id=\"avg20\" value=\"".number_format($avg20, 2)."\" /></td>
<td><input type=\"text\" size=10 id=\"avg40\" value=\"".number_format($avg40, 2)."\" /></td>
<td><input type=\"text\" size=10 id=\"avg60\" value=\"".number_format($avg60, 2)."\" /></td>
<td><input type=\"text\" size=10 id=\"avg80\" value=\"".number_format($avg80, 2)."\" /></td>
<td><input type=\"text\" size=10 id=\"avg100\" value=\"".number_format($avg100, 2)."\" /></td>
<td><input type=\"submit\" name=\"averageAdd\" value=\"Add Averages\" onclick=\"addAverages('{$var}');\"/></td>
<td></td></tr>
</table><br />");

$count = 1 + $s ;
echo "<table width=&#34;1024&#34; border=&#34; 1 &#34; align=&#34;center&#34;>";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["Keyword"];
$fu = $row["Title"];
$bar = $row["Price"];
$dat = $row["Date"];
$lnk = $row["Item"];
$rcd = $row["RECNO"];

echo "<tr id=\"$rcd\"><td style='width: 50px;'>$count.)</td><td>$title</td><td>$fu</td><td>&#36;$bar</td><td>$dat</td><td>
<a href=\"http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=" . $lnk . "\" target=\"_blank\">Click Here</a></td><td>
<a href = # onclick=checkName('{$rcd}')> Del </a></td></tr>";

$count++ ;
}

$currPage = (($s/$limit) + 1);

//break before paging
echo "</table>";

// Query to determine lowest price
$query2 = "SELECT Price, MIN(Price) FROM CleanDataCombined2010";
$result2 = mysql_query($query2) or die("Couldn't execute query");
echo "<p>Lowest is $result2</p>";

// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print "&nbsp;<a href=\"search.php?s=$prevs&next=$var&q={$_GET['q']}\">&lt;&lt;
Prev 10</a>&nbsp;&nbsp;";
}

// calculate number of pages needing links
$pages=intval($numrows/$limit);

// $pages now contains int of pages needed unless there is a remainder from division

if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}

// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {

// not last page so give NEXT link
$news=$s+$limit;

echo "&nbsp;<a href=\"search.php?s=$news&next=$var&q={$_GET['q']}\">Next 10 &gt;&gt;</a>";
}

$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}// else numrows = 0
echo("</div>");
}//returnData

function calculatePercentile($list, $amount){
// the formula used Y(p) = Y[k] + d(Y[k+1] - Y[k])
// p(N+1) = k + d
$precision = (func_num_args() == 3) ? func_get_arg(2) : 2;
sort($list);
if($amount <= $list[0]){
return "1.00";
}else if($amount >= $list[(sizeof($list)-1)]){
return "99.00";
}else{
$k = FALSE;
foreach($list as $key=>$value){
if(($amount >= $value) && ($amount < $list[($key+1)])){
$k = $key;
}
}
if(!($k === FALSE)){
$d = (($amount/($list[$k+1]-$list[$k]))/($list[$k]/($list[$k+1]-$list[$k])));
$p = (((($k+1)+$d)/(sizeof($list)+1))*100);
return number_format($p,$precision);
}else{
return FALSE;
}
}
}//calculatePercentile

//this function will find the average
//for a numerical array
function findAverage($array){

//the total number of items
$count = count($array);

$total = 0;

//now sum up the array
foreach($array as $i){

$total = $total + $i;

}//foreach

//return the average
if($count != 0){
return($total/$count);
}//if
else{
return(0);
}//else

}//findAverage

?>
</div>

<script type="text/javascript">

var RecoverScroll=/*28432953204368616C6D657273*/
{

timer:null, x:0, y:0,cookieId:"RecoverScroll", dataCode:0, DEBUG:false,

init:function(pageName)
{
var offsetData;

if( document.documentElement )
this.dataCode=3;
else
if( document.body && typeof document.body.scrollTop!='undefined' )
this.dataCode=2;
else
if( typeof window.pageXOffset!='undefined' )
this.dataCode=1;

if(pageName)
this.cookieId=pageName;

if((offsetData=this.readCookie(this.cookieId))!=""
&& (offsetData=offsetData.split('|')).length==4
&& !isNaN(offsetData[1]) && !isNaN(offsetData[3]))
{
window.scrollTo(offsetData[1],offsetData[3]);
if(this.DEBUG)
document.title=offsetData;
}

this.record();
this.addToHandler(window,'onscroll',function(){RecoverScroll.reset()});
},

reset:function()
{
clearTimeout(this.timer);
this.timer=setTimeout("RecoverScroll.record()",500);
},

record:function()
{
var cStr;

this.getScrollData();

this.setTempCookie(this.cookieId, cStr='x|'+this.x+'|y|'+this.y);

if(this.DEBUG)
window.status=cStr;
},

setTempCookie:function(cName, cValue)
{
document.cookie=cName+"="+cValue;
},

readCookie:function(cookieName)
{
var cValue="";

if(typeof document.cookie!='undefined')
cValue=(cValue=document.cookie.match(new RegExp(cookieName+'=([^;]+);?'))) ? cValue[1] : "";

return cValue;
},

getScrollData:function()
{
switch( this.dataCode )
{
case 3 : this.x = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
this.y = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
break;

case 2 : this.x=document.body.scrollLeft;
this.y=document.body.scrollTop;
break;

case 1 : this.x = window.pageXOffset; this.y = window.pageYOffset; break;
}
},

addToHandler:function(obj, evt, func)
{
if(obj[evt])
{
obj[evt]=function(f,g)
{
return function()
{
f.apply(this,arguments);
return g.apply(this,arguments);
};
}(func, obj[evt]);
}
else
obj[evt]=func;
}
}
RecoverScroll.addToHandler(window,'onload',function(){RecoverScroll.init("search.php")});

//this function adds the values of the average textboxes to the database
//it calls the file averages.php which actually does the work.
function addAverages(searchString){

//get the values
var avg20 = document.getElementById("avg20").value;
var avg40 = document.getElementById("avg40").value;
var avg60 = document.getElementById("avg60").value;
var avg80 = document.getElementById("avg80").value;
var avg100 = document.getElementById("avg100").value;

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){

alert ("Your browser does not support AJAX!");
return;

}//if xml null

//pass the values to the file and call it
var url="average.php";
url=url+"?pass20="+avg20;
url=url+"&pass40="+avg40;
url=url+"&pass60="+avg60;
url=url+"&pass80="+avg80;
url=url+"&pass100="+avg100;
url=url+"&searchString="+searchString;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=function () {stateChanged("averageOutput");};
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

}//addAverages

//this function runs when the user clicks the delete link
function checkName(id){

if(window.confirm("Are you sure, this cannot be undone?")){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){

alert ("Your browser does not support AJAX!");
return;

}//if xml null

var url="delete.php";
url=url+"?deleteId="+id;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=function () {stateChanged(id);};
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}//if window.confirm

}//checkName

//this function runs when the select box is changed
function callReturnData(type){

//first we have to clear anything in the output div
document.getElementById("outputDiv").innerHTML="";

if(type == "drop"){
var input = document.getElementById("select").value;
outputNextLink(input);
}//if
else{
var input = document.getElementById("inputText").value;
}//else

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){

alert ("Your browser does not support AJAX!");
return;

}//if xml null
document.getElementById("select").value = input;
var url="returnData.php";
url=url+"?passedSearchData="+input;
url=url+"&type="+type;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=function () {stateChanged("outputDiv");};
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

//write the ebay button
document.getElementById("ebaySearch").innerHTML = "<a href=\"http://completed.shop.ebay.com/i.html?_nkw="+input+"&_sacat=4670&LH_Complete=1&_odkw=icom&_osacat=4670&_trksid=p3286.c0.m270.l1313\" target=\"_blank\">Search on Ebay</a>";

}//callReturnData
function outputNextLink(data){
document.getElementById("outputLink").innerHTML = data;
}//outputnextLink
function ebaySearch(input){

var altered = escape(input);
window.location="http://completed.shop.ebay.com/i.html?_nkw="+input+"&_sacat=4670&LH_Complete=1&_odkw=icom&_osacat=4670&_trksid=p3286.c0.m270.l1313";


}//ebaySearch
function stateChanged(id){

if (xmlHttp.readyState==4){

document.getElementById(id).innerHTML=xmlHttp.responseText;
}//if readyState

}//stateChanged

function GetXmlHttpObject(){
var xmlHttp=null;

try {

// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();

}//try

catch (e){

// Internet Explorer
try{

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

}//try

catch (e){

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}
}//catch

return xmlHttp;

}//getxml objec

</script>
</body>
</html>

LifeinAsia

10:42 pm on Feb 18, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Can you edit your post to just include the relevant part of the code?

andrewsmd

11:00 pm on Feb 18, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I figured that was coming, but I was trying to be lazy :). It's got to be something with my php or ajax because if I just run basic html it works. I'll start commenting things out until I can figure it out.

Fotiman

1:59 am on Feb 19, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The first thing I would do is change this:

<div id=\"outputLink\"></div>

to this:

<div id="outputLink"></div>

That might fix it.

andrewsmd

2:26 pm on Feb 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just a typo. The slashes were in there because that was actually in a php echo i.e.
echo("<div id=\"outputLink\"></div>");

Fotiman

2:30 pm on Feb 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can you post just the output from the PHP? In other words, view the page in a browser and do View > Source.

andrewsmd

3:02 pm on Feb 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ahhh looks like I needed the ol step away and come back to it. I came in this morning and realized I had copied the div tag from my echo and put it pasted in as <div id=\"outputLink\"></div> Thanks for the help everyone.