JavaScript - Returning Ajax Data Performed Function?
Scenario:
Client Side : Simple functions that have events tied to different elements. Each time an event is triggered the function begins an Ajax call to an external server side page filled with JS functions. Server Side : Our client side AJAX call sends the name of the function we want to call out on this file. Once called and performed, it returns DOM edits that could be fired once our client side page receives the data back from Ajax. I know that data being returned from Ajax is always a string. But would it be possible? I mean could the server side file send out commands or rather DOM edits that the client side could pick up on and perform? I am almost 100% certain the answer is no due to JS needing to be cached in the browser and what not, but I figured I would ask the experts anyways. BTW: objective is to move sensitive core JS functions to prevent online application theft... without Flex or Air. Similar TutorialsHey guys..... My skill level on JavaScript is only intermediate so maybe this is really obvious.... but it's driving me nuts & I can't work it out. Heres some example code.. Code: function createAJAXobject() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { /* alert("Cannot create object in IE."); */} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { /* alert("Cannot create object in IE."); */} try { return new XMLHttpRequest(); } catch(e) { /* alert("Cannot create object in Mozilla."); */} alert("XMLHttpRequest is not supported."); return null; } function ajaxRequest(url) { // Create AJAX object var myAJAX = createAJAXobject(); // Retrieve data myAJAX.open("GET",url,true); myAJAX.onreadystatechange = function() { // Was it a success? if (myAJAX.readyState < 4) { return false; } // Set results var res = myAJAX.responseText; /* Returns results */ if (res != '') { return res; // Correctly enters this part via testing // Output of the variable 'res' here outputs correct text } else { return false; } } myAJAX.send(null); } function searchCats(text) { // Set URL for ajax request var url = 'search_cats.php?search_text='+text; // Set up element we're modifying var results = document.getElementById('cat_list'); // Send the request var ajaxResponse = ajaxRequest(url); alert(ajaxResponse); // = undefined } I have included comments in the above explaining my problems..... the data is correct when I use alert() just before I return it, but when I use alert inside the function that calls it I get "undefined" & the error in FireFox says "ajaxResponse" is undefined. Please please someone help! Hi everyone, I have a hunch that my function is not returning the string value. Below runs some information about the code: getvalues_2() - A function that recognizes the value of the string selected by the user from the drop down list and sends it to a variable. Variable name is 'groom_profession' here. Based on the value (text) returned, it assigns a particular number to the variable 'profession' in this case. But, I have been noticing that irrespective of the value chosen from the drop down list, the variable 'profession' is assigned a default value from the switch case statement. I know the variable (textval_2) is able to store the correct value from the drop down list with the help of an alert command. But, it fails while returning the value. I even tried initializing the string in the function body but to no avail. What could be wrong here? Following is the code for one of the drop-down lists: Code: <b> Groom's current Profession </b> <FORM NAME="Profession"> <SELECT NAME="Groomprofession" onchange = "getvalues_2()"> <OPTION VALUE="c1">Select </OPTION> <OPTION VALUE="c2">Doctor </OPTION> <OPTION VALUE="c3">Engineer </OPTION> <OPTION VALUE="c4">Lawyer </OPTION> <OPTION VALUE="c5">CA </OPTION> <OPTION VALUE="c6">IAS </OPTION> <OPTION VALUE="c7">Engineer + MBA </OPTION> <OPTION VALUE="c8">Family Business </OPTION> <OPTION VALUE="c9">None of the above </OPTION> </SELECT> </FORM> Following is the code for function getvalues_2() declaration: Code: <script type = "text/javascript"> function getvalues_2() { var val_2 = document.Profession.Groomprofession.value; var si_2 = document.Profession.Groomprofession.selectedIndex; if (si_2 != 0) { var textval_2 = " "; textval_2 = document.Profession.Groomprofession.options[si_2].text; //alert (val_2); // for testing //alert (textval_2); // for testing return (textval_2); } } </script> Following is the code for the switch case statement: Code: <script type="text/javascript"> var profession; groom_profession = getvalues_2(); switch(groom_profession) { case "Engineer" : profession = 1.8; break; case "Doctor" : profession = 1.9; break; case "Lawyer" : profession = 1.65; break; case "CA" : profession = 1.7; break; case "IAS" : profession = 2.0; break; case "Family Business" : profession = 1.5; break; case "Engineer + MBA" : profession = 1.95; break; case "None of the above" : profession = 1.95; break; default: profession = 0.6; } </script> The website has a total of 11 drop-down lists (so 11 functions like getvalues, and 11 switch case statements. I thought if I could get one to work, the others might follow suit too). I would be really grateful if someone could look into my problem and suggest where I am going wrong. Thanks a lot! I am wondering how can I return the variable senttext from the function below? I have declared it and when I alert(senttext) below it appears as I want it but I need to return it and pass it to another function. When I change alert() to return the variable becomes undefined??? var senttext; function getData() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open('GET',"http://www.site6.certcoordering1.com/Download/recall.txt" ); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { senttext ='<table style="border:thin black solid"><tr><td><h2>Recent</h2></td><td><h2>Recalls</h2></td><td></td><td></td></tr>' ; var ad2 = req.responseText.split("\n"); for(i=0; i<ad2.length-1; i++) { // now split by comma var ad3 = ad2[i].split(","); senttext += '<tr><td><p>'+ad3[0]+'</p></td><td> <a href="http://www.site6.certcoordering1.com/Download/'+ad3[2]+' rel="nofollow" target="_blank">'+ad3[1] +'</a></td><td></td></tr>' } senttext += '</table>' ; alert(senttext); // I need to return senttext, not alert! When I send it it becomes undefined? } else { alert('File did not load correctly.'); } } } req.send(""); } 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. I find it odd that this function is returning the day as 1, when it is clearly the 28th. when I run the code the answer I get looks like this: 1-Feb-2011 9:27 Code: function getDateTime(when) { var theDate = new Date(); var day = theDate.getDay(); var month = theDate.getMonth(); var year = theDate.getFullYear(); var myTimeArr = theDate.toTimeString().split(":"); var monthNumber = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") when.value = day + "-" + monthNumber[month] + "-" + year + " " + myTimeArr[0] + ":" + myTimeArr[1]; any advice? Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. My page is he http://acq.matthewboehler.com/ I have jQuery script written on my page to create a fade-effect when an image is hovered. See the large, kitchen image in the middle of the screen to see this effect in action. This is done on images with the "fade" class and styled with the second image as its background image. My problem is when I apply the "fade" class to another image, the background image does not appear on a rollover. See the bottom left corner image, when you rollover it goes away. Can someone explain why? hey all, I am now at the point of being able to see the light at the end of the tunnel (woot!). After a lot of help from you guys I have tackled my RSS feed issue (sort of) to the point where i have a page that does basically what I need it to (http://www.the-rational-investor.com/test042311.php/). I now need to incorporate this java script developed into the big picture and of course, there seems to be problems. Since I know it works on its own, I must be running into problems getting all the functions working simultaneously and I once again need to call on the board's brilliance in figuring out what I am doing wrong....so here it goes I have taken out a lot of unnecessary code just to focus on the java script. Yes there is PHP code embedded but please don't beat up on me too much for that. here is the main page code: Code: <head> <? // function for onmouseover to do ALL THREE tasks // ?> <script type="text/javascript"> function doChanges(y){ var z= y; var imagevar = myimages[z]; var imagethis = this.href; changeimage(imagevar,imagethis); changetext(z); var x=y; var rssfeedvar = myArrayRssFeed[x]; showRSS(rssfeedvar); } </script> <? // First Task - function for onmouseover TEXT // ?> <script type="text/javascript"> function changetext(z){ var s= z; var textchangeEntries = myArrayEntries[s]; var id = document.getElementById("DBtext_large"); id.innerHTML=textchangeEntries; var textchangeWebadr = myArrayWebadr[s]; var id = document.getElementById("DBtext_link").getElementsByTagName('a')[0]; id.nodeValue=textchangeWebadr; id.setAttribute('href',textchangeWebadr); id.innerHTML=textchangeWebadr; var textchangeEmail = myArrayEmail[s]; var id = document.getElementById("DBtext_email"); id.innerHTML=textchangeEmail; var textchangeRssUrl = myArrayRssUrl[s]; var id = document.getElementById("DBtext_rssUrl"); id.innerHTML=textchangeRssUrl; var textchangeRssFeed = myArrayRssFeed[s]; var id = document.getElementById("DBtext_rssFeed"); id.innerHTML=textchangeRssFeed; } </script> <? // Second Task - functions for onmouseover IMAGES // ?> <script type="text/javascript"> function changeimage(towhat,url){ if (document.images){ document.images.targetimage.src=towhat.src gotolink=url } } function warp(){ window.location=gotolink } </script> <script type="text/javascript"> var myArrayEntries = ["<?php echo implode('","',$map_entry_array);?>"]; var myArrayWebadr = ["<?php echo implode('","',$web_adr_array);?>"]; var myArrayEmail = ["<?php echo implode('","',$email_adr_array);?>"]; var myArrayRssUrl = ["<?php echo implode('","',$rss_url_array);?>"]; var myArrayRssFeed = ["<?php echo implode('","',$rss_feed_array);?>"]; var myimages=new Array() var gotolink="#" function preloadimages(){ for (i=0;i<preloadimages.arguments.length;i++){ myimages[i]=new Image() myimages[i].src=preloadimages.arguments[i] } } preloadimages(<?echo("$qs1");?>); </script> <? // Third Task - functions for onmouseover RSS FEED // ?> <script type="text/javascript"> function showRSS(str) { if (str.length==0) { document.getElementById("rssOutput").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("rssOutput").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getrss.php?q="+str,true); xmlhttp.send(); } </script> </head> getrss.php is unchanged Code: <?php //get the q parameter from URL $q=$_GET["q"]; //find out which feed was selected if($q=="http://twitter.com/statuses/user_timeline/53777622.rss") { $xml=("http://twitter.com/statuses/user_timeline/53777622.rss"); } elseif($q=="http://www.autisticsociety.org/rss/news2.php") { $xml=("http://www.autisticsociety.org/rss/news2.php"); } elseif($q=="http://sableresources.com/news/") { $xml=("http://sableresources.com/news/"); } elseif($q=="http://www.northgateminerals.com/rss/pressrelease.aspx") { $xml=("http://www.northgateminerals.com/rss/pressrelease.aspx"); } elseif($q=="http://www.thompsoncreekmetals.com/s/RSS.asp?MaxItems=4&Version=RSS2.0") { $xml=("http://www.thompsoncreekmetals.com/s/RSS.asp?MaxItems=4&Version=RSS2.0"); } elseif($q=="http://www.imperialmetals.com/s/RSS.asp?MaxItems=10&Version=RSS2.0") { $xml=("http://www.imperialmetals.com/s/RSS.asp?MaxItems=10&Version=RSS2.0"); } elseif($q=="http://investorrelations.walterenergy.com/corporate.rss?c=71978&Rule=Cat=news~subcat=ALL") { $xml=("http://investorrelations.walterenergy.com/corporate.rss?c=71978&Rule=Cat=news~subcat=ALL"); } elseif($q=="http://www.teck.com/framework/comp.aspx?portalName=tc&id=133613&rss=1") { $xml=("http://www.teck.com/framework/comp.aspx?portalName=tc&id=133613&rss=1"); } elseif($q=="http://www.tasekomines.com/tko/RSS.asp?MaxItems=10&Version=RSS2.0") { $xml=("http://www.tasekomines.com/tko/RSS.asp?MaxItems=10&Version=RSS2.0"); } elseif($q=="http://www.rocamines.com/s/RSS.asp?MaxItems=10&Version=RSS2.0") { $xml=("http://www.rocamines.com/s/RSS.asp?MaxItems=10&Version=RSS2.0"); } elseif($q=="http://www.breakwater.ca/rss/pressrelease.aspx") { $xml=("http://www.breakwater.ca/rss/pressrelease.aspx"); } $xmlDoc = new DOMDocument(); $xmlDoc->load($xml); //get elements from "<channel>" $channel=$xmlDoc->getElementsByTagName('channel')->item(0); $channel_title = $channel->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue; $channel_link = $channel->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue; $channel_desc = $channel->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue; //output elements from "<channel>" echo("<p><a href='" . $channel_link . "'>" . $channel_title . "</a>"); echo("<br />"); echo($channel_desc . "</p>"); //get and output "<item>" elements $x=$xmlDoc->getElementsByTagName('item'); for ($i=0; $i<=2; $i++) { $item_title=$x->item($i)->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue; $item_link=$x->item($i)->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue; $item_desc=$x->item($i)->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue; echo ("<p><a href='" . $item_link . "'>" . $item_title . "</a>"); echo ("<br />"); echo ($item_desc . "</p>"); } ?> Thanks again for all your wonderful help and all the best to you and your families on this Easter weekend, Brian Hi there How to send data from a text feild in GET method using an AJAX call... I already have codes working Code: to = "interfaces/add_department.jsp"; parm = "name="+name.value+ "&name2="+name2.value; alert(parm) post(to,parm,callBackFunctionForAddDepartment); Here the variable name may have "me&you" or "me you" like that.... so how do i encode it so that it reaches properly? Hi, I've created a function that calls to get data from my MySQL database. If there is no data in my MySQL database, I want the page to just keep refreshing and then if it finds the data, I want it to echo it to the page. I'll post my code below and it'll give you an idea of what's going on. <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> $.ajax({ url: 'retrieve.php', data: "", dataType: 'json', success: function(data) { var videoid = data[0]; if (videoid == false) { setTimeout("location.reload(true);",1000); } else { $('#youtube').html("<iframe width='400' height='225' src='http://www.youtube.com/embed/"+videoid+"?rel=0&autohide=1&showinfo=0' frameborder='0' allowfullscreen></iframe>"); } } }); </script> </head> <body onload="$.ajax();"> <div class="container"> <div id="youtube"> <!----- checkServer() output appears here !-----> </div> </div> </body> So as you can see the idea is that if there is a video id present in the database, it echoes the embed code for the YouTube video. If the database is empty, it just keeps refreshing the page. However this not what's happening. At the moment it just keeps echoing an empty YouTube video onto the page. I think it has something to do with my if and else syntax? Thanks for any help you can give. Also I apologize in advance if this a retarded way of doing things. I just need a basic proof concept before I make this code work any better. Hello all; Sorry if this is in the wrong forum, but I'm using a little bit of everything in this problem. What I have is an ajax function using JQuery that references to a separate PHP file, which also contains mySQL. Here is my code: Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> </head> <body> <div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div> <script> function addtask() { var tid = (Math.floor(Math.random() * 3)) + 1; var tsk = (Math.floor(Math.random() * 10)) + 1; if(tsk !== 1) { $.ajax({ type: "POST", url: "taskcheck.php", dataType: "json", data: {taskid:tid}, success: function(task) {alert(task.name);} }); } } </script> </body> </html> What is happening is when the ajax function is called, the PHP runs fine and the mySQL adds the necessary data to the table, but the success function is not running. Here is the referenced PHP (taskcheck.php): PHP Code: session_start(); $connect = mysql_connect('x', 'x', 'x') or die('Not Connecting'); mysql_select_db('x') or die ('No Database Selected'); $task = $_REQUEST['taskid']; $uid = $_SESSION['user_id']; $q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1"; $gettask = mysql_fetch_assoc(mysql_query($q)); $q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)"; $puttask = mysql_fetch_assoc(mysql_query($q)); $json = array( "name" => $gettask['taskname'] ); $output = json_encode($json); echo $output; If you have any more questions about the problem please let me know, and any suggestions or comments would be greatly appreciated. Thanks! Hi, I have a problem with sending data from a form to a php script with AJAX. To test if it works, I try to send data from the form, print it in the php with "echo", and then put it back in the initial html file. My Javascript code is: Code: function registerPrivateUser() { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support AJAX!"); return; } var postData="firstName="+ document.getElementById("txtFirstName").value; var url="classes/users/checkRegistration.php"; xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("POST",url,true); //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); xmlhttp.send(postData); } The function stateChanged, basically says: Code: if (xmlhttp.readyState==4) { var strResponse; strResponse=xmlhttp.responseText; alert('Response:' + xmlhttp.responseText); } checkRegistration.php looks like this: PHP Code: <? session_start(); $firstName=$_POST['firstName']; echo($firstName); ?> The problem is that the response is empty, but I don't know why. I have checked the input data and the postData variable says "firstName="+input (e.g. "firstName=Robert"), so that's not the error. I have read several forum posts here, but still haven't figured out what I'm doing wrong. If anyone could please tell me, I would appreciate it alot. I am doing a project and I have a problem. I have retrieved data from a json file using ajax and the xmlhttprequest, but I am not able to put the content I retrieve into the dojo content pane. The content pane is inside a border container. I have tried the following, but it does not work. The HTMLPage4.html has the json data inside. please help me really urgent to me!!!!!!!as soon as possible Code: function getInfoContent(graphic) { function ajaxRequests() { var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) for (var i = 0; i < activexmodes.length; i++) { try { return new ActiveXObject(activexmodes[i]) } catch (e) { //suppress error } } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc return new XMLHttpRequest() else return false } var mygetrequests = new ajaxRequests() mygetrequests.onreadystatechange = function() { if (mygetrequests.readyState == 4) { if (mygetrequests.status == 200 || window.location.href.indexOf("http") == -1) { var bookss = eval("(" + mygetrequests.responseText + ")") //retrieve result as an JavaScript object var rssent = bookss.infos.info for (var i = 0; i < rssent.length; i++) { // alert(mygetrequests.responseText); var placeImg = "" var txt = "" // placeImg += rssent[i].descImg txt += rssent[i].desc var shorttxt = "" shorttxt += txt.substring(0, 30); var bc = new dijit.layout.BorderContainer({ style: "font-size: 11pt; height: 574px; width:739px; border:0px;" }); var c1 = new dijit.layout.ContentPane({ region: "top", style: "height: 11.5%; width: 100%; color: black; background-color: transparent; border:0px;", content: "<table><div id = \"mydiv\">" + shorttxt + "<font color = '#0000FF' size = '1'><a onclick='showmore();'><u> More...</u></a></div></td></table>" }); bc.addChild(c1); } } else { alert("An error has occured making the request") } } return bc.domNode; } mygetrequests.open("GET", "HTMLPage4.htm", true) mygetrequests.send(null) } I'm using jquery right now but I sort of understand what the problem is. I'm making a file manager and when you click on an li tag it will do some action depending on if it's a file type or a folder type. There are 3 important files you should know about. 1. filemanager.php (Where the file managing takes place. Starts by including filemanager_getfile.php and including filemanager.js in the head). 2. filemanager_getfile.php (Information that receives information from the ajax request [the directory to be read] and prints the new file list in <li> tags) 3. filemanager.js (Jquery that processes li clicks) The problem is, when you click on a folder (and it loads the new information from the ajax request) the jquery doesn't check the new li tags when clicked (I'm guessing when you first link the javascript file it has to compile all of the current li information?). Try it for yourself- [removed] Instruction (if it's not already obvious): -Clicking a file selects if. If files are selected and you click the arrow in the file options it will transfer it (not really, but it will later). -Clicking a folder will send an ajax request with the new directory information to be checked and return the html -Clicking the '?' in the file options will display the pages html (I implemented it to debug). I have tried linking the js page every time I include the new directory information, but the js stacks on each other. So if I click on 3 folders and hit the '?' button it will display the page html 3 times. And if I select the index.php li and click transfer, it will "transfer" 3 times. filemanager.php Code: <div id="goldenSub"> <div class="title">Golden Subdomain</div> <div class="files" id="goldenSubFiles"> <? include("filemanager_getfiles.php"); ?> </div> <div id="history" visited="goldensub/"></div>; <div class="fileOptions"><img src="images/question.png" title='HTML Information' id="ask"><img src="images/transferto.png" title='Copy File To' id="transferTo"></div> </div> filemanager_getfiles.php PHP Code: <? $path = $_REQUEST["dir"]; if($path == "" || $path == null) { $path = 'goldensub/'; } echo "\n<div class='path'>$path</div>\n<ul>\n"; $handler = opendir($path); //We need to organize the results. Be default, all files and folders will be //located by alphabetical order. But we want to list all folders first, followed //by files. By adding the results to arrays first we can decide to print our //results in the order we want. $folderArray = array(); $fileArray = array(); $folderCount = 0; $fileCount = 0; while(false !==($file=readdir($handler))) { if($file != "" && $file != null && $file != "." && $file != "..") { $extensionLocation = strrpos($file, "."); //Is this a folder or a file? if($extensionLocation == null && $extensionLocation == "") { //This is a folder unless it's the error_log file. if($file != "error_log") { //Nope, it's definitly a folder. Add it to the folder array. $folderCount++; $folderArray[$folderCount] = $file; } } else { //This is a file. Add it to the file array. $fileCount++; $fileArray[$fileCount] = $file; } } } if($path != 'goldensub/') { echo "\t<li title='goldensub/' type='folder'>\n\t\t<img src='images/up.png'> goldensub\n\t</li>\n"; } for($i = 1; $i<=$folderCount; $i++) { $newPath = $path.$folderArray[$i].'/'; echo "\t<li title='$newPath' type='folder'>\n\t\t<img src='images/folderOpen.png'> $folderArray[$i]\n\t</li>\n"; } for($i = 1; $i<=$fileCount; $i++) { $extensionLocation = strrpos($fileArray[$i], "."); $nameLength = strlen($fileArray[$i]); $extensionLength = $nameLength-$extensionLocation; $nameClean = substr($fileArray[$i], 0, $extensionLocation); $extension = substr($fileArray[$i], $extensionLocation+1, $nameLength); echo "\t<li title='$fileArray[$i]' type='file' extension='$extension'>\n\t\t\n\t<img src='images/$extension.png'> $nameClean\n\t</li>\n"; } echo "</ul>"; ?> filemanager.js Code: $("li").click(function(){ var type = $(this).attr("type"); //This is a folder if(type == "folder") { //Path to new directory var newPath = $(this).attr("title"); //Ajax request to filemanager_getfiles.php $("#goldenSubFiles").load("filemanager_getfiles.php", { dir: newPath }, function(data){ //Update log newLog("Directory changed to <i><b>"+newPath+"</b></i>"); }); } //This is a file else { if($(this).hasClass("selected")) { //It's already selected - deselect it. $(this).removeClass("selected"); } else { //Select it $(this).addClass("selected"); } } }); 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, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me overview: from my javascript, i call a function in the php block, that function successfully retrieves a value from the database, but when i pass that retrieved value back to the calling function....all is lost somehow. when i test this code by itself, it works fine and gets the correct number. <?php mysql_select_db($database_connFtH, $connFtH); $result = mysql_query("SELECT status_index FROM cpqc_status ORDER BY row_id DESC"); $row_result = mysql_fetch_assoc($result); $index = $row_result['status_index']; echo $row_result['status_index']; echo $index; echo "the value of index is ".$index; ?> however, when i set this same code up as a function to be called upon globally, and to return the value of $index, it all just seems to "not work". <?php function runStatus() { mysql_select_db($database_connFtH, $connFtH); $result = mysql_query("SELECT status_index FROM cpqc_status ORDER BY row_id DESC"); $row_result = mysql_fetch_assoc($result); $index = $row_result['status_index']; return ($index); } //end function runStatus() ?> the calling function, with an alert box to check if the value of $index was passed down accurately <script type="text/javascript"> var x = runStatus(); alert(x); </script> all i want to do is call a server-script function that deals with the database and gets me a value out of the database, and pass that value back to the calling function. can't figure out what is wrong. the "return($index)" should send back the value of $index. the call to that function should receive back a value and assign it to "x". and the alert(x) should spit it out with no problem. but......something is wrong and it won't work. any ideas what is wrong? it is my understanding that a function inside the php determants can be called upon from anywhere and that function can return a value.(?) argh!! i think i know why Einstein's hair was always so messy!! thanks, Paul Williams weather today in Kalispell, MT: 7 deg this morning, got a little snow last night, only about 6 or 8 inches, not much. maybe more later. I m trying to send data to my database (Mysql). When I enter things in the prompt box it doesn t go to my database. Can someone tell me why, please? Here is my code: <script type="text/javascript"> function show_prompt() { var name=prompt("question"); if (name!=null && name!="") { //set the hidden input value to the value entered in the prompt document.input.purpose.value = name; //document.input referring to the form named 'input' document.input.submit(); //submit the form } } </script> <form id="propose" name="input" action="insertpropose.php" method="post"><br/> <input type="submit" onclick="show_prompt()" value="propose" /> <input type="hidden" name="propose" value=""> </form> and the insertpropose.php form is: $propose=$_POST['propose']; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO propose VALUES ('','$propose')"; mysql_query($query); mysql_close(); Hey all i am in need of some help trying to figure out how to pass a string into an array field for a chart. The chart i am using is this [http://www.highcharts.com/] Here is the chart code: Code: function drawChart(theDATA) { var chart = new Highcharts.Chart({ chart: {renderTo: 'container',defaultSeriesType: 'column'}, title: {text: 'March 2010 Confirmed User Visit\'s'}, xAxis: {categories: ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']}, yAxis: {min: 0,title: {text: 'User Visit\'s'}}, legend: {layout: 'vertical',backgroundColor: '#FFFFFF',style: {left: '100px',top: '70px',bottom: 'auto'}}, tooltip: {formatter: function() {return this.y;}}, plotOptions: {column: {pointPadding: 0.2,borderWidth: 0}}, series: [{name: 'Confirmed Users Visit\'s', data: theDATA.split(',') }] }); } With the code above, you would think that theDATA would work but it does not display the data within it. Say that theDATA is '2,5,4,7,8,9'. If i had this: Code: data: [2,5,4,7,8,9] Then it would work just fine. But if i use those same numbers... Code: theData = "2,5,4,7,8,9" data: theDATA.split(',') It does nothing on the chart... So what am i doing wrong???? David Hi, i'm having a problem with calling a netbeans function through an URL, that saves data to a postgresql table that has 119 columns. This is the original link: Code: http://www.mirodinero.com:8080/mirodinero-war/setMisDatos?callback=respuestaGuardarMisDatos¶m=%26usuario%3DIsa%20Mirodinero%26nivel%3D109%26gano_sal_neto%3D211113.45%26gano_sal_prof%3D2480%26gano_monet%3D0%26gano_renta_fija%3D0%26gano_renta_vble%3D0%26gano_inmuebles%3D2226.75%26gano_otros%3D2223.73%26gano_otros_ing%3D2411.12%26porc_gano_monet%3D0%26porc_gano_rentaf%3D0%26porc_gano_rentav%3D0%26porc_gano_inm%3D2%26porc_gano_otros%3D2%26porc_gano_otros_ing%3D1%26gasto_casa1%3D1306.46%26gasto_casa2%3D2402.38%26gasto_casa3%3D3999.57%26gasto_prestamo1%3D93475.58%26gasto_prestamo2%3D7325.88%26gasto_prestamo3%3D34090.9%26gasto_tarjetas%3D29443.2%26gasto_ibi%3D5670%26gasto_imp_otros%3D6780%26gasto_seg_inm%3D1320%26gasto_seg_pens%3D3451.22%26gasto_seg_vida%3D2330%26gasto_seg_plan%3D34230%26gasto_seg_medico%3D21220%26gasto_seg_coche%3D220%26gasto_luz%3D620%26gasto_agua%3D4550%26gasto_gas%3D320%26gasto_telef_f%3D22320%26gasto_telef_m%3D2350%26gasto_internet%3D20%26gasto_tv%3D3450%26gasto_hogar%3D20%26gasto_comida%3D20%26gasto_cenas_copas%3D20%26gasto_viajes%3D20%26gasto_vacaciones%3D220%26gasto_mobiliario%3D220%26gasto_ropa%3D2320%26gasto_transp%3D230%26gasto_otros%3D3620%26gasto_colegios%3D240%26gasto_univ%3D340%26gasto_master%3D2230%26gasto_otros_gastos%3D7323433%26porc_gasto_tarjetas%3D0%26porc_gasto_ibi%3D0%26porc_gasto_trib%3D0%26porc_gasto_seg_inm%3D0%26porc_gasto_seg_pens%3D0%26porc_gasto_seg_vida%3D2%26porc_gasto_seg_plan%3D2%26porc_gasto_seg_med%3D0%26porc_gasto_seg_coche%3D0%26porc_gasto_sum_luz%3D2%26porc_gasto_sum_agua%3D2%26porc_gasto_sum_gas%3D0%26porc_gasto_sum_teleff%3D0%26porc_gasto_sum_telefm%3D0%26porc_gasto_sum_int%3D0%26porc_gasto_sum_tv%3D0%26porc_gasto_nivel_hogar%3D0%26porc_gasto_nivel_comida%3D0%26porc_gasto_nivel_cenas%3D0%26porc_gasto_nivel_viajes%3D0%26porc_gasto_nivel_vacac%3D0%26porc_gasto_nivel_mob%3D0%26porc_gasto_nivel_ropa%3D20%26porc_gasto_nivel_transp%3D30%26porc_gasto_nivel_otros%3D30%26porc_gasto_colegios%3D2%26porc_gasto_univ%3D0%26porc_gasto_master%3D0%26porc_gasto_otros_gastos%3D23%26tengo_casa1%3D1231.11%26tengo_casa2%3D10000%26tengo_casa3%3D22240%26tengo_otras%3D23560%26tengo_monetario%3D1212.34%26tengo_planpensiones%3D23230%26tengo_otros%3D23330%26porc_tengo_casa1%3D1%26porc_tengo_casa2%3D0%26porc_tengo_casa3%3D2%26porc_tengo_otras%3D0%26porc_tengo_monet%3D0%26porc_tengo_plan%3D0%26porc_tengo_otros%3D0%26debo_casa1%3D4340%26debo_casa2%3D23450%26debo_casa3%3D23430%26debo_prestamo1%3D23330%26debo_prestamo2%3D6871.11%26debo_prestamo3%3D11340%26debo_tarjetas%3D61340%26porc_debo_casa1%3D30%26porc_debo_casa2%3D10%26porc_debo_casa3%3D12%26porc_debo_prestamo1%3D1%26porc_debo_prestamo2%3D12%26porc_debo_prestamo3%3D1%26porc_debo_tarjetas%3D4%26plazo_debo_casa1%3D230%26plazo_debo_casa2%3D450%26plazo_debo_casa3%3D122%26plazo_debo_prestamo1%3D3%26plazo_debo_prestamo2%3D12%26plazo_debo_prestamo3%3D4 It's 2568 characters long, so i guess that's why i get sometimes a GET undefined method in the web console. The original function does something like this: Code: var param ="&usuario="+usuario+"&nivel="+nivel+gano+porc_gano+gasto+porc_gasto+tengo+porc_tengo+debo+porc_debo+plazo_debo; var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = server_direction +"setMisDatos?callback=respuestaGuardarMisDatos¶m="+encodeURIComponent(param); var h = document.getElementsByTagName("script")[0]; h.parentNode.insertBefore(s, h); //or h.appendChild(s); and every variable in the param is written like this: Code: var plazo_debo_casa1 = (getValor("plazo_debo_casa1")); var plazo_debo_casa2 = (getValor("plazo_debo_casa2")); var plazo_debo_casa3 = (getValor("plazo_debo_casa3")); var plazo_debo_prestamo1 = (getValor("plazo_debo_prestamo1")); var plazo_debo_prestamo2 = (getValor("plazo_debo_prestamo2")); var plazo_debo_prestamo3 = (getValor("plazo_debo_prestamo3")); var plazo_debo ="&plazo_debo_casa1="+plazo_debo_casa1+"&plazo_debo_casa2="+plazo_debo_casa2+"&plazo_debo_casa3="+plazo_debo_casa3+"&plazo_debo_prestamo1="+plazo_debo_prestamo1+"&plazo_debo_prestamo2="+plazo_debo_prestamo2+"&plazo_debo_prestamo3="+plazo_debo_prestamo3; since my webpage has different parts where to put the data, i thought that a good idea would be to create smaller function for parts of variable, for example putting 30 variables and the do the callback. I did like this: Code: function guardaLoQueGano(){ var nivel = parseInt(document.getElementById('progreso_nivel_total').style.marginLeft); /*idUsusario*/ var usuario = miGetElementsByClassName('title', document.getElementById('block-user-1'))[0].innerHTML; /*gano*/ var gano_sal_neto = getValor("gano_sal_neto"); var gano_sal_prof = getValor("gano_sal_prof"); var gano_monet = getValor("gano_monet"); var gano_renta_fija = (getValor("gano_renta_fija")); var gano_renta_vble = (getValor("gano_renta_vble")); var gano_inmuebles = (getValor("gano_inmuebles")); var gano_otros = (getValor("gano_otros")); var gano_otros_ing = (getValor("gano_otros_ing")); /*gano porcentajes*/ var porc_gano_monet = getValor("porc_gano_monet"); var porc_gano_rentaf = getValor("porc_gano_rentaf"); var porc_gano_rentav = getValor("porc_gano_rentav"); var porc_gano_inm = getValor("porc_gano_inm"); var porc_gano_otros = getValor("porc_gano_otros"); var porc_gano_otros_ing = getValor("porc_gano_otros_ing"); var param = "&usuario=" + usuario + "&nivel=" + nivel + "&gano_sal_neto=" + gano_sal_neto + "&gano_sal_prof=" + gano_sal_prof + "&gano_monet=" + gano_monet + "&gano_renta_fija=" + gano_renta_fija + "&gano_renta_vble=" + gano_renta_vble + "&gano_inmuebles=" + gano_inmuebles + "&gano_otros=" + gano_otros + "&gano_otros_ing=" + gano_otros_ing + "&porc_gano_monet=" + porc_gano_monet + "&porc_gano_rentaf=" + porc_gano_rentaf + "&porc_gano_rentav=" + porc_gano_rentav + "&porc_gano_inm=" + porc_gano_inm + "&porc_gano_otros=" + porc_gano_otros + "&porc_gano_otros_ing=" + porc_gano_otros_ing; var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = direccion_servidor + "setMisDatos?callback=respuestaGuardarMisDatos¶m=" + encodeURIComponent(param); var h = document.getElementsByTagName("script")[0]; // adesso h.appendChild(s); h.parentNode.insertBefore(s, h); alert("Datos de lo que gano actualizados correctamente"); } This kind of function works perfectly, but has a big problem: it changes the values of the columns of this function, but deletes the remaining ones. How can I create different smaller function, in a way to save only on some columns without changing the others? Shall I write the netbeans function setMisDatos to make it more clear? |