JavaScript - Function Name Undefined
New to javascript, so I'm trying to work through a rather older, but helpful nonetheless book entitled "Head Rush Ajax".
I'm only finishing up the first chapter...lol and my code is not doing what its supposed to be doing. I'm sure its something simple like a typo, but I have been over it several times and cant spot the problem. When I try to run the script in IE8, it throws an error saying object expected. line 43 code 0 Here is my complete script. According to the book I should be able to click the button and the values will update only once. PHP Code: var request = null; function createRequest() { try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) alert("Error creating request object!"); } function getBoardsSold() { createRequest(); var url="getUpdatedBoardSales-ajax.php"; request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); } function updatePage() { if (request.readyState == 4) { var newTotal = request.responseText; var boardsSoldEl = document.getElementById("boards-sold"); var cashEl = document.getElementById("cash"); replaceText(boardsSoldEl, newTotal); // Figure out how much cash katie has made var priceEl = document.getElementById("price"); var price = getText(priceEl); var costEl = document.getElementById("cost"); var cost = getText(costEl); var cashPerBoard = price - cost; var cash = cashPerBoard * newTotal; //update the cash for the slopes on the form cash = Math.round(cash * 100) / 100; replaceText(cashEl, cash); } } Thanks for any help in advance! Similar Tutorialsi keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> Hi, so I have this function: Code: function centerZoom() { var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < gmarkers.length; i++) { if (!gmarkers[i].isHidden()) { var point = gmarkers[i].getPoint(); bounds.extend(point); } map.setZoom(map.getBoundsZoomLevel(bounds)); map.setCenter(bounds.getCenter()); } } which I call he Code: for (var j = 0; j < gmarkers.length; j++) { var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); centerZoom(); } which I thought was pretty straightforward, but I keep getting a "centerZoom is undefined" message. The only place I don't get that is if I take it out of the initialize sequence, but it doesn't work then anyway (and from what I understand, being that it contains var bounds = new... it has to go in initialize. Here's the rest of the page, if anybody has any ideas ok im having a bit of problem with this. code : <input type="hidden" value="&nsbp;" name="b1r1c1"> (insde a table} <td></script>function ba1r1c1() { document.write(b1r1c1.value); }</script></td> (later on) <script> ba1r1c1(); </script> Whats happening is its not writing the space inside the cell but somewhere else on the page but i dont know why. The table is inside <div> tags if that helps. any help apreciated. Thanks hi here is a code i use to calculate distance b//w 2 places using google api... it works perfectly and shows the results in the html but when i add a return statement at the end of the function showlocation() it returns undefined.. why it is so.. how to resolve it??? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,follow" /> <title>Calculate driving distance with Google Maps API</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAMK3PClIOG6IUkYprx4EfNxSY_HQRLXr6AGORx7Qh39w3-je8JxRROt5eJTcDPJ9nGnVn9xXKTQ2l8Q" type="text/javascript"></script> <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> <script type="text/javascript"> var geocoder, location1,addr1,addr2, location2, result1,gDir; function coolAl(add1,add2) { addr1=add1; addr2=add2; var result= return initialize(); showLocation(); alert(result); } function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; result1=location1.address + ' (' + location1.lat + ':' + location1.lon + ')/' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')/' + drivingDistanceKilometers + ' kilometers'; document.body.innerHTML=result1; return drivingDistanceKilometers; }); } function showLocation() { geocoder.getLocations(addr1, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(addr2, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); } </script> </head> <body onload="coolAl('pune','mumbai')"> </html> Suppose we have following javascript codes: Case 1. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar; } var bar_ref= foo(); document.write(bar_ref()); // it pops up "hello" and print-outs "undefined". If we modified above code slightly, shown as follow: Case 2. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar(); } var bar_ref= foo(); document.write(bar_ref()); // it only pops up "hello". As you can see, Case 2 modified the return value from "return bar" to "return bar()," which won't cause the "undefined" output. To me, it looks like when the JS interpreter executes the line "bar_ref();" it triggers the execution of function "foo", besides both "return bar" and "return bar()" do the same job which is to execute function body of "bar". The only difference is that after the execution of function bar, its function body does not exist anymore, so when the interpreter executes the line "return bar;" it follows the function identifier "bar" and ends up with "undefined". This is why the Case 1 gives us "undefined", but I am not quite clear about why the Case 2 can trace down to the function body of "bar". Do you have any ideas about such difference outputs? Dan Hi.. I encountered problem in using $_GET to get the DATE_PROCESS. here is my code: Code: <script> function editloan(){ var dateprocess = document.getElementById('dateprocess').value; alert(dateprocess); window.location = "SSSLoan.php?dateprocess="+dateprocess; } </script> Code: <div id="searchname"> <form> <p class="serif"><b>Search Lastname:</b></p> <input type="text" name="ssssearch" size="20" onkeyup="fetchsuggest(this.value);"> <div> <hr /> <ul id="suggest" style="overflow:auto; height:380px; width:auto;"> {section name=co_emp loop=$personalAll} <li><a href="SSSgetdata.php?queryEmpID={$personalAll[co_emp].EMP_ID}">{$personalAll[co_emp].FULLNAME}</a></li> <hr /> {sectionelse} <li>No records found</li> {/section} </ul> </div> </div> <div id="loanformmain"> <input type="button" name="sssbtn" value="SSS" onclick="loanFrm()"> <input type="button" name="hdmfbtn" value="HDMF" onClick="hdmfloanFrm()"> <input type="button" name="UTbtn" value="Union Dues/Trust Fund" onclick="utloanFrm()"> </div> <div id="sssloan"> <fieldset> <legend>SSS Loan</legend> <p class="serif"> <label id="SSSLabel">SSS ID</label><label id="EMPIDLabel">EMP ID</label><label id="NAMELabel">NAME</label><label id="LOANLabel">LOAN</label><label id="AMORLabel">DEDUCTION</label> <input type="text" name="SSS" value="{$sss}" size="8" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="EMP_NO" value="{$empno}" size="8" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="NAME" value="{$fullname}" style="background: #e2e2e2" readonly="readonly" size="35"> <input type="text" name="LOAN" value="{$LOAN}" size="9"> <input type="text" name="AMOR" value="{$AMOR}" size="9"> <input type="button" name="add" value="ADD" onclick="SSSAdd()"> <input type="hidden" name="dateprocess" value="{$dateprocess"> </p> </legend> </fieldset> <div style="overflow:auto; height:300px; width:auto;"> <p> <table border="1" class="stat"> <tr> <td colspan="4" style="text-align:center">SSS ID</td> <td colspan="4" style="text-align:center">EMP ID</td> <td colspan="15" style="text-align:center">NAME</td> <td colspan="4" style="text-align:center">LOAN</td> <td colspan="4" style="text-align:center">DEDUCTION</td> <td colspan="4" style="text-align:center">DATE PROCESS</td> </tr> {section name=att loop=$getsss} <tr> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSS}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].EMP_NO}</td> <td colspan="15" style="background: #e2e2e2" readonly="readonly">{$getsss[att].FULLNAME}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSSLoan}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSSAmor}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly" id="dateprocess" onclick="editloan('{$getsss[att].DATE_PROCESS}')">{$getsss[att].DATE_PROCESS}</td> </tr> {sectionelse} <tr><td colspan="1">No DATA</td></tr> {/section} </table> <table border="1"> <tr> <td colspan="4" style="text-align:center"><b>TOTAL:</b></td> <td colspan="5" style="background: #e2e2e2" readonly="readonly">{$Total_Loan}</td> </tr> </table> </p> </form> </div> </div> Code: <?php include 'config.php'; $currentEmpID = $_SESSION['empID']; $sql = "SELECT EMP_ID, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME, SSS, HDMF, TIN FROM PERSONAL WHERE EMP_ID='$currentEmpID'"; $recPersonal = $conn->Execute($sql); if (!$recPersonal) { print $conn->ErrorMsg(); } if (!$recPersonal->BOF) { $recPersonal->MoveFirst(); } $sss = trim($recPersonal->fields['SSS']); $hdmf = trim($recPersonal->fields['HDMF']); $tin = trim($recPersonal->fields['TIN']); $smarty->assign('sss', $sss); $sql = "SELECT EMP_ID, CONCAT(LNAME, ', ' , FNAME, ' ', MI) AS FULLNAME FROM PERSONAL ORDER BY LNAME ASC"; $recPersonalNav = $conn->GetAll($sql); $smarty->assign('personalAll', $recPersonalNav); // ======================================================================================================================== $sql = "SELECT em.EMP_NO, p.EMP_ID, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME FROM PERSONAL p, EMPLOYMENT em WHERE p.EMP_ID='$currentEmpID' AND em.EMP_ID = '$currentEmpID'"; $recPersonalHead = $conn->Execute($sql); $fullName = $recPersonalHead->fields["FULLNAME"]; $empno = $recPersonalHead->fields["EMP_NO"]; $smarty->assign('empid', $currentEmpID); $smarty->assign('fullname', $fullName); $smarty->assign('empno', $empno); //===============================SELECT SSSLoan=================================== $dateprocess = $_GET['dateprocess']; $sql = "SELECT s.EMP_NO, s.SSSLoan, s.SSSAmor, s.DATE_PROCESS FROM $PAYROLL.sssloan s, $ADODB_DB.employment em WHERE em.EMP_NO= s.EMP_NO AND s.DATE_PROCESS = '$dateprocess'"; $rsloan = $conn2->Execute($sql); $LOAN = trim($rsloan->fields['SSSLoan']); $AMOR = trim($rsloan->fields['SSSAmor']); $dateprocess = $rsloan->fields['DATE_PROCESS'] ; $smarty->assign('LOAN', $LOAN); $smarty->assign('AMOR', $AMOR); $smarty->assign('dateprocess', $dateprocess); //============================SELECT ALL DATA FOR SSSLOAN========================== $sql = "SELECT s.EMP_NO, em.EMP_ID, p.SSS, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME, s.SSSLoan, s.SSSAmor, s.DATE_PROCESS FROM $ADODB_DB.PERSONAL p, $ADODB_DB.employment em, $PAYROLL.sssloan s WHERE s.EMP_NO = em.EMP_NO AND p.EMP_ID = '$currentEmpID' AND em.EMP_ID = '$currentEmpID'"; $rs = $conn2->GetAll($sql); $smarty->assign('getsss', $rs); $sql = "SELECT s.EMP_NO, SUM(SSSAmor) AS Total_Loan FROM $PAYROLL.sssloan s, $ADODB_DB.employment em WHERE em.EMP_NO = s.EMP_NO AND em.EMP_ID = '$currentEmpID'" or die (mysql_error()); $rsTotal = $conn2->Execute($sql); $Total_Loan = $rsTotal->fields['Total_Loan']; $smarty->assign('Total_Loan', $Total_Loan); $smarty->display('header.tpl'); $smarty->display('loanForm.tpl'); $smarty->display('footer.tpl'); exit(); ?> when I click date in <td colspan="4" style="background: #e2e2e2" readonly="readonly" id="dateprocess" onclick="editloan('{$getsss[att].DATE_PROCESS}')">{$getsss[att].DATE_PROCESS}</td> it result no value...it did not get the value that I click Thank you in advance The following coding works in Konqueror 3.5.10 on Ubuntu 8.04.3 LTS but not on Firefox 3.0.10 Linux/3.5.7 XP, Opera 10.10 Linux or IE8 XP. I can't see why but it may be to do with the recursion (showtable calls onclick calls addit which calls showtable ...). Somehow it is not seeing the addit routine the second time round. It is meant just to add a line. Eventually it needs to be a complex table but this is for illustration. There are other ways to solve this but this would be the simplest - if it worked! What happens is that one line is added OK but then it chokes. This is what makes me think it is the recursion but I can't see otherwise how to make it write the updated text. I realise I should have a document.close() in it as well and I have tried adding <![CDATA[ ... ]]> as well. Other than in Konqueror, it gives an error message saying object not found (in IE8) or more explicitly: Code: function onclick(event){ addit(4); } with 'addit is not defined' in Firebug. In Konqueror it works sweetly. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <script language='Javascript' type='text/javascript'> if(typeof(sections) == 'undefined'){ var sections=['Text 0','Text 1','Text 2']; } function addit(ilocal){ sections.splice(sections.length,0,'Text '+ilocal); showtable(); } function showtable(){ var i,j,ip1; for(i=0;i<sections.length;i++){ ip1=i+1; document.write('Section ',i,': ',sections[i],'<br>'); } document.write("<input type='button' value='Add' onClick='addit(",ip1,")' /><br>"); for(j=0;j<sections.length;j++){document.write(sections[j]," ");} } </script> </head><body> <script language='Javascript' type='text/javascript'> showtable(); </script> </body> </html> Clues would be very much appreciated - my baldness coefficient is increasing daily! Hello, I'm hoping someone can help me with this. I have 3 pages that I need to put into my framework, they are products, shopping cart and billing. At the moment they work perfectly fine. Here is a live example - http://www.cems.uwe.ac.uk/~r4-george...g/products.php Now, I have a framework for a whole website that I need to put these pages into. (http://www.cems.uwe.ac.uk/~r4-george/wp4/index.php) The index uses a switch statement to go between pages. Here is the index.php PHP Code: <?php # index.php /* * This is the main page. * This page includes the configuration file, * the templates, and any content-specific modules. */ // Require the configuration file before any PHP code: require_once ('./modules/config.inc.php'); // Validate what page to show: if (isset($_GET['p'])) { $p = $_GET['p']; } elseif (isset($_POST['p'])) { // Forms $p = $_POST['p']; } else { $p = NULL; } // Determine what page to display: switch ($p) { case 'about': $page = 'about.inc.php'; $page_title = 'About This Site Again'; break; case 'products': $page = 'products.inc.php'; $page_title = 'Products on this site'; break; case 'this': $page = 'this.inc.php'; $page_title = 'This is Another Page.'; break; case 'that': $page = 'that.inc.php'; $page_title = 'That is Also a Page.'; break; case 'contact': $page = 'contact.inc.php'; $page_title = 'Contact Us'; break; case 'search': $page = 'search.inc.php'; $page_title = 'Search Results'; break; // Default is to include the main page. default: $page = 'main.inc.php'; $page_title = 'Site Home Page'; break; } // End of main switch. // Make sure the file exists: if (!file_exists('./modules/' . $page)) { $page = 'main.inc.php'; $page_title = 'Site Home Page'; } // Include the header file: include_once ('./includes/header.inc'); echo "<div id=\"content\">"; // Include the content-specific module: // $page is determined from the above switch. include ('./modules/' . $page); // Include the footer file to complete the template: include_once ('./includes/footer.inc'); ?> It uses the .inc.php files located in the modules folder to switch between pages. Here is my products.inc.php - PHP Code: <? include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){ $pid=$_REQUEST['productid']; addtocart($pid,1); header("location:shoppingcart.php"); exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Products</title> <script language="javascript"> function addtocart(pid){ document.form1.productid.value=pid; document.form1.command.value='add'; document.form1.submit(); } </script> </head> <body> <form name="form1"> <input type="hidden" name="productid" /> <input type="hidden" name="command" /> </form> <div align="center"> <h1 align="center">Products</h1> <table border="0" cellpadding="2px" width="600px"> <? $result=mysql_query("select * from products"); while($row=mysql_fetch_array($result)){ ?> <tr> <td><img src="<?=$row['picture']?>" /></td> <td> <b><?=$row['name']?></b><br /> <?=$row['description']?><br /> Price:<big style="color:green"> £<?=$row['price']?></big><br /><br /> <input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" /> </td> </tr> <tr><td colspan="2"><hr size="1" /></td> <? } ?> </table> </div> </body> </html> This is EXACTLY the same code as the working example. The products get listed correctly but the problem I have is the 'Add to Cart' button fails to work. Live example - http://www.cems.uwe.ac.uk/~r4-george...php?p=products Everything is in the right directory. When I inspect the 'Add to Cart' button in chrome I get the following - Quote: Uncaught TypeError: Cannot set property 'value' of undefined addtocart index.php:51 (anonymous function)index.php:83 onclick Any help is really appreciated, I'm struggling to see what I have done wrong. I don't know whether it's a Javascript problem. If you need any of the code from other pages I can post it too. Thanks in advance. I have a function where in I call another function that assigns a value to a var. e.g. Code: function setVar{ var thisVar = 'hello'; return thisVar; } function callFuncSetVar { var newVar = setVar(); alert(newVar); } For some reason my code below is returning 'undefined'. But when I place an alert(); before the 'return' it shows the correct value. However when I place an alert(); to show the var that is set to what the function returns it says 'undefined'. Firebug throws no errors. I am using a little bit of jQuery. Whenever i try to use this function it gives me either - NaN, or undefined what am i doing wrong? The objective of these functions are to change x and y coordinates into SAN (Simplified Algebraic Notation) for use in the Chess Game's DataFile (PGN file format). Live Running DHTML App: http://daomingjin.googlepages.com/ChessManager.html 140kb Zip-Archive: http://daomingjin.googlepages.com/ScoreMatev1.zip here are the functions in Question: Code: function XCoordToSAN(x) { // Convert the x coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var xCoord = 0; xCoord > xCoord * 7; xCoord++) { if(x == xCoord * BlockSize) { var SANx = xCoord; } } return SANx; } function YCoordToSAN(y) { var Letters = ["A", "B", "C", "D", "E", "F", "G", "H"]; // Convert the y coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var yCoord = 0; yCoord > yCoord * 7; yCoord++) { if(y == yCoord * BlockSize) { var SANy = Letters[yCoord]; } } return SANy; } this is how i'm calling the functions: Code: var oldPGNx = XCoordToSAN(oldXposition); var oldPGNy = YCoordToSAN(oldYposition); var newPGNx = XCoordToSAN(newXposition); var newPGNy = YCoordToSAN(newYposition); NewPGNData = oldPGNx + oldPGNy + "-" + newPGNx + newPGNy + " "; // Finally update the Data document.getElementById("PGNArea").value = OldPGNData + NewPGNData; I have a slideshow that allows the user to see the previous slide title and the next slide title along with the current slide and its content. I tested locally not in WP and the code worked fine. Once I placed my source within WP everything went south. I inspector the first line in the script seems to be what is having the issues - $(window).load(function(){ and I am unsure what to do next. The source was used from Edit fiddle - JSFiddle the page I am trying to get to work is located here - Sevices | Q&D CONSTRUCTION, INC.Q&D CONSTRUCTION, INC. I am open to any suggestions. Code: <script type='text/javascript' src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/20130801/jquery.cycle2.min.js"></script> <style type='text/css'> .cycle-slide { width: 100%; text-align: center; } img { max-width: 300px; } #next { float: right; } #prev { float: left; } .center { text-align: center; } </style> <script type="text/javascript">//<![CDATA[ $(window).load(function(){ var slideshow = $('.cycle-slideshow'); maxSlides = slideshow.data('cycle.opts').slideCount; slideshow.on({ 'cycle-update-view': function(event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) { UpdateTitles(); } }); function UpdateTitles(){ var currentSlide = slideshow.data('cycle.opts').currSlide; activeSlide = $(".cycle-slide-active"); activeTitle = activeSlide.data('title'); if(currentSlide == 0){ nextTitle = activeSlide.next().data('title'); prevTitle = $(".cycle-slide").eq(maxSlides).data('title'); } else if(currentSlide == maxSlides-1){ prevTitle = activeSlide.prev().data('title'); nextTitle = $(".cycle-slide").eq(0).data('title'); } else { nextTitle = activeSlide.next().data('title'); prevTitle = activeSlide.prev().data('title'); } $('h1').html(activeTitle); $('#prev').html("Previous: "+prevTitle); $('#next').html("Next: "+nextTitle); } UpdateTitles(); });//]]> </script> Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Hello, When I run the following code, the .Length function returns "undefined." Please help! This is driving me crazy. Code: var strTest = 'test'; alert(strTest.Length); Using the typeof function, I know that JS is treating the variable as a string. Any suggestions? I know I shouldn't be having this problem at this stage. But what have I done wrong? I have my main page, I have my onload page and in that onload page I call a function: And then I get the error message: Fatal error: Call to undefined function OpenChat() The main page code (I've cut out the irrelevant scripts); Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $Sfullname=$_SESSION['fullname']; $SMyPId=$_SESSION['MyPId']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html> <title></title> <head> <script type="text/javascript"> function OpenChat(Msg){ loadgetdiv(); document.getElementById('<?php echo $Newdiv; ?>').style.display="block"; loadChatComplex('<?php echo $NewThisFile; ?>','<?php echo $Newdiv; ?>',Msg); } </script> <script type="text/javascript"> function loadChatCheck(File,ID,Tile,TID){ loadQuickCheck(File,ID); dodo = setInterval(function(){loadQuickCheck(Tile,TID)},5000); } </script> <script type="text/javascript"> function loadQuickCheck(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; malaky = setInterval(function(){loadQuickCheck(File,ID)},20000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> </head> <body onload="loadChatCheck('getCheckNewMessages.php','txtHintCheckNewMessage','getFriendsOnline.php','txtHintShowFriends')"> <div class="mainpage"> <?php include("headermenu.php"); ?> <div id="txtHintShowFriends"></div> <div id="txtHintCheckNewMessage"></div> <br /><br /> </body> </html> AND the onload/getCheckNewMessages.php is PHP Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $SMyPId=$_SESSION['MyPId']; include("dbconnect.php"); $result = mysql_query("SELECT COUNT(*) as newchat FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); $row = mysql_fetch_assoc($result); $total=$row['newchat']; echo 'This is ' . $total .'<br />'; if ($total >=1){ $result = mysql_query("SELECT * FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); while($row = mysql_fetch_array($result)){ $doormouse=$doormouse . ';' . $row['ChatID']; } $listees=explode(';',$doormouse); foreach($listees as $listor){ echo 'This is ' . $listor . '<br />'; $result = mysql_query("SELECT * FROM chat INNER JOIN allusers ON chat.chatter=allusers.PId WHERE chat.ChatID='{$listor}' "); while($row = mysql_fetch_array($result)){ echo "{$SMyPId};{$row['chatter']};{$row['fullname']};{$row['ref']}"; } echo $battlebox . '<br />'; $steptoe=OpenChat($battlebox); } $sql="UPDATE chat set stat='' WHERE ChatID='{$chatID}' "; mysql_query($sql,$con) or die(mysql_error()); } ?> Needless to say I am trying to create an instant chat. Hi, My webpage can work normally in IE but not in Safari(e.g. when I clicked on some buttons like 'Delete' button, the page opened in Safari stays the same while it should delete the object chosen). When I tried debugging on Safari, after clicking the 'update' button, this message error appeared: "TypeError: Result of expression 'this.form.fireEvent' [undefined] is not a function". I believe this code makes the incompatability between the 2 browser: Code: function DeleteClick() { var frmSWO = document.getElementById("form"); var answer = confirm("Do you really want to delete?") if (answer != 0) { frmSWO.action = "/domsWeb/mtd/doms/web/operation/eDepotMNR/controller/manageWorkOrder/DeleteJobOrImage.do"; frmSWO.method = "post"; this.form.fireEvent('onsubmit'); frmSWO.submit(); } } Any suggest how should I amend the script for it to work on 2 browser concurrently? Thanks all! Here is a clip of code from a script project im working on. Now my document.getElementsByTagName is returning a "undefined" value. Can anyone tell me whats wrong with my code? Code: <a href="http://www.anotherrandomsite.com" style="text-decoration: none; color: #EDDBAF; font-size: 16px;"> <center style="margin-left: 10px; margin-right: 10px;"> <font style="color: #EDDBAF; font-size: 16px;" id="title"></font> </center> </a> <li id="name"><a http="http://www.randomsite.com" style="color: blue;">John Doe</a></li> <script type="text/javascript"> var pname = document.getElementById('name').getElementsByTagName('a'); //now if i remove the ".getElementsByTagName('a')" it will actually work, but it also includes the <a> tag thats within the <li> tag, which i dont want. document.getElementById('title').innerHTML=pname.innerHTML; </script> Hi everyone, I'm using a JavaScript to upload multiple files, namely this one: http://valums.com/ajax-upload/ The script has the ability to post additional parameters to the server, by calling the function setParams Code: var doktyp = "default"; var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-scope'), action: 'uploads.php', // additional data to send, name-value pairs debug: true, onSubmit: uploader.setParams ({ dateityp: getCheckedValue(document.forms['doktyp'].elements['dateityp']), comment: jQuery('#dateityp').val() }) }); Without the onSubmit: part the script works well and does as it's supposed to, but with it FireBug reports "uploader is undefined" und the script seizes to function. Now JavaScript istn't my strong suit, so I have been reading up on this for the last two hours, tried calling that function from a different place, tried to modify it, but no luck; the error remains the same (or slightly different; if I point at the class in question directly, the function doesnt work...). I would appreciate any advice you could give. Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. Hi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave |