JavaScript - Returning Text From Responsetext Xmlhttprequest Function?
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(""); } Similar TutorialsAJAX XMLHttpRequest responseText returns undefined but alert returns expected text. Code: function getFile(fileToOpen) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { //alert(xmlhttp.responseText); return xmlhttp.responseText; } } xmlhttp.open("GET",fileToOpen,true); xmlhttp.send(null); } Code: document.getElementById('widgetOptionsShadow').innerHTML = '<div id="widgetOptions">' + getFile('/togglePauseInit.php?g=<?php echo $gadgetName; ?>') + '</div>'; I heard there is something called XMLHttpRequest that is compatible to all browsers. What does that actually do? Is there something to do with Javascript? Thank you.
Hey 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! 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. 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? How can I get the selected text of a textarea with JavaScript? example: Code: <form name="reportForm"> <textarea name="report"></textarea> <br /> <input type="button" onClick="GetSelectedText();" /> </form> Thanks IC Dear Forum Guys, I have a problem regarding how to recieve multiple response texts from an Ajax code. That is: I want to recieve multiple "responseText"s from the ajax code so that i can populate my form in an asp page. I would also like to know how i can send multiple asp or javascipt Variables inside the responseText of an Ajax code, so that when ajax does responseText i could use the variables just sent from another page (i.e the variables are recieved by the same ajax code after doing responseText) to do some specific tasks. Thank you. Hello guys, i really need help with my code...i was stuck with it for like 4 hours >< I want to display the content of my text file inside the html page in the div tags so i could place it somewhere around th page or change it style etc. Could anyone please help? And another question : Are there any chances to display my text data, which is one number in the input box ? Quote: <HTML><HEAD> <SCRIPT language = "Javascript"> objXml = new ActiveXObject("Microsoft.XMLHTTP"); var datafile = "G:\data.txt"; objXml.open("GET", datafile, true); objXml.onreadystatechange=function() { if (objXml.readyState==4) { display(objXml.responseText); } } objXml.send(null); function display(msg) { mydiv.innerHTML = msg ; } </SCRIPT> <BODY> <input type='button' onclick='display(msg)' value='Display'/> <div id="mydiv"></div> </BODY> </HTML> RESOLVED Thank you! Greetings all! Im looking for some help regarding responseText, so please have a look im so mad right now because i have been struggeling for hours XMLHttpRequestObject.responseText returns correct value when i do alert(XMLHttpRequestObject.responseText); see line PHP Code: var fnWhenDone = function (XMLHttpRequestObject) { alert(XMLHttpRequestObject.responseText); }; But problem is that i want to save down the response to a variable... so i try to change it into PHP Code: var fnWhenDone = function (XMLHttpRequestObject) { varTest = XMLHttpRequestObject.responseText; }; When i try to alert varTest later i get "Undifined"... im pretty new to javascript and have been stuck for hours ... See full code below PHP Code: var myConn = new XHConn(); if (!myConn) { alert("XMLHTTP not available. Try a newer/better browser."); } var fnWhenDone = function (XMLHttpRequestObject) { alert(XMLHttpRequestObject.responseText); }; myConn.connect("validateSearch.php", "POST", "foo=bar&baz=qux", fnWhenDone); function XHConn() { var xmlhttp, bComplete = false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }}} if (!xmlhttp) return null; this.connect = function(sURL, sMethod, sVars, fnDone) { if (!xmlhttp) return false; bComplete = false; sMethod = sMethod.toUpperCase(); try { if (sMethod == "GET") { xmlhttp.open(sMethod, sURL+"?"+sVars, true); sVars = ""; } else { xmlhttp.open(sMethod, sURL, true); xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1"); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && !bComplete) { bComplete = true; fnDone(xmlhttp); }}; xmlhttp.send(sVars); } catch(z) { return false; } return true; }; return this; } Edit: Nevermind
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> I'm starting to learn javascript and trying to get the below code to work with newer browsers. I'm not sure how to implement the below to make it work with XMLHttpRequest. There is a small form that uses this function to allow you to select an xml file to load. Your help is much appreciated. Thanks. Code: function importXML() { if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.onload = createQuiz; } else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.onreadystatechange = function () { if (xmlDoc.readyState == 4) createQuiz() }; } else { alert('Your browser cannot handle this script'); return; } xmlDoc.load(document.getElementById('file').value); } I tried posting this same thread under AJAX and I didn't get a single response. I am wondering if it may be in the wrong section so I decided to try here. If this is bad posting etiquette, I apologize. Hello. I am trying to use a form to submit values to MySQL and then have a Google map returned that has certain parameters. I have modeled this code after an example I found on w3schools. I believe that this is strictly a javascript coding problem. This is the code that I am using: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ Page Language="C#" %> <html dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #filter { height: 5%; width: 73%; margin-top: 5px; margin-left: 2%; border: 3px solid black; padding: 1%; overflow: auto } #txtHint { height: 20%; width: 73%; margin-top: 5px; margin-left: 2%; border: 3px solid black; padding: 1%; overflow: auto } #maplist { height: 60%; width: 75%; margin-top: 5px; margin-left: 2%; border: 3px solid black } </style> <script type="text/javascript"> function showTrail(str) { if (str=="") { document.getElementById("maplist").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) { alert(xmlhttp.responseText); } } xmlhttp.open("GET","traillist2.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <div id="filter"> <form name="filterform"> <select id="scenery" onchange=""> <option value="">Select Scenery Rating:</option> <option value="a">A</option> <option value="b">B</option> <option value="c">C</option> <option value="d">D</option> <option value="f">F</option> </select> <select id="length" onchange=""> <option value="">Select Trail Length</option> <option value="g">Less than 1</option> <option value="h">1-2.9</option> <option value="i">3-4.9</option> <option value="j">5-6.9</option> <option value="k">7-8.9</option> <option value="l">More than 9</option> </select> <select id="difficulty" onchange=""> <option value="">Select Trail Difficulty</option> <option value="m">Easy</option> <option value="n">Moderate</option> <option value="o">Strenuous</option> </select> <input id="combined" type="button" value=" Find Trail! "onclick="showTrail(this.form['scenery'].value + this.form['length'].value + this.form['difficulty'].value)"/> </form> </div> <div id="maplist"></div> </body> </html> The code is designed to drop the map into the "maplist" div. In the code above, you see that I have the line "alert(xmlhttp.responseText);" which was originally: document.getElementById("txtHint").innerHTML=xmlhttp.responseText;" I wrote the php page so it would return code as shown below. This is the actual responseText received from the alert. Code: script type="text/javascript"> var map; function initialize() { var latlng = new google.maps.LatLng(34.65, -83.9); var options = { zoom: 9, center: latlng, mapTypeId: google.maps.MapTypeId.TERRAIN }; var infoWindow = new google.maps.InfoWindow; var html; var map = new google.maps.Map(document.getElementById('map_canvas'), options); var point = new google.maps.LatLng( parseFloat(34.558350), parseFloat(-84.250122)); var marker = new google.maps.Marker({ position : point, map : map, icon : 'http://labs.google.com/ridefinder/images/mm_20_red.png' }); var html = '<div><br><b>Amicalola Falls State Park - Creek Trail</ b><br><br><b>Trail Length: </b>0.5 miles<br><b>Scenery Rating: </b>C<br><b>Difficulty Rating: </ b>Easy<br><b>Trail Features: </b>Stream<br><br><font size:large><font face="Tahoma, Geneva, sans-serif" size="1" color="#000071"><strong><a href="http://www.digitaltrailguide.com/ amicalolafallsstateparkcreekmountainlaurelspringtrails.aspx">View This Trail</a></strong></font></div>'; bindInfoWindow(marker, map, infoWindow, html); function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); } } function loadScript() { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://maps.google.com/maps/api/js? sensor=false&callback=initialize"; document.body.appendChild(script); } window.onload = loadScript; </script>I thought that this code would be dropped into the div and Ok, so I have built a website using galleryCMS, a pre-built CMS for images, which outputs XML via php to an address of: http://www.granitesupermarket.ca/login.php/view/xml Firefox and Chrome can pull the XML from the webpage using my code, however IE does nothing with it at all. I have found that if I use a page with a proper xml extension then the code works fine (ie test.xml); however, without the .xml it seems like IE does nothing?? I am not the most advanced user, so tampering with the CMS is not the best option for me... is there any workaround that I might be able to employ? Maybe a way I could take the xml I get from "login.php/view/xml" and save it to gallery.xml on the same server? Any help or ideas would be helpful. Code: <html> <head> <title></title> <head> <body> <script type="text/javascript"> // Get XML function function loadXMLDoc(dname) { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",dname,false); xhttp.send(); return xhttp.responseXML; } // XML source xmlDoc=loadXMLDoc("login.php/view/xml") t=xmlDoc.getElementsByTagName("thumbnail"); // TEST THAT XML IS WORKING document.write(""+ t[0].childNodes[0].nodeValue + ""); </script> </body> </html> Hi there, Im looking for a general function which would work for most browsers when using the xmlhttprequest() I am just trying to send input data to the server store it and send back a response. I have one that works for both ie and ff, however when using ff the function does not return the text from the request to the server, but does with ie no problems. Any help would be much appreciated. Thanks Code: /* get response http request */ function getData(cURL) { var xmlHttp = null; xmlHttp = new XMLHttpRequest(); /* branch logic for ff or ie */ if (navigator.appName=='Netscape') lSynch = true; else lSynch = false; xmlHttp.open( "POST", cURL, lSynch ); xmlHttp.send( null ); var info = xmlHttp.responseText; return info; } I've been working for some time trying to get XMLHTTPRequests to work. Nothing doing. The code seems simple enough, but I can't duplicate it on my own. I have two pages on the same PC. Code to follow. Please help me see the problem: Page One - Originator <code> <html> <head> <title>Origination</title> <script type='text/javascript'> function ajaxRequest(){ 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; } //Usage: //new ajaxRequest() function getStuff() { var getdata = new ajaxRequest(); if (getdata.readyState==4){ if (getdata.status==200){ var htmldata=getdata.responseText var txtfields = htmldata.getElementsByTagName('input'); alert(txtfields); } else{ alert('An error has occured making the request'); } } getdata.open('POST', 'test.html', true); getdata.send(null); } </script> </head> <body> <h5>Origination</h5> <form <form action="file:///test.html" method="post" enctype="text/plain"> <input type='text' name='homepage' value=''/> <input type='button' name='getit' value='GetSome' onclick='getStuff()'/> </form> </body> </html> </code> Page Two - The Target Page: <code> <html> <head><title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/> <script type="text/javascript" src=" http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"/> <style type="text/css"> html {font-family: arial; font-size: 0.8em; } </style> </head> <body> <div id="wrapper"> <form action="file:///eyec.html" method="post" enctype="text/plain"> <input type='text' name='first' value='First Field'/> <input type='text' name='second' value='Second Field'/> <input type='text' name='third' value='Thrird Field'/> <input type='text' name='fourth value='Fourth Field'/> </form> </div> <!-- wrapper --> </body> </html> </code> I'd deeply appreciate correction. Thanks. hello all, I am trying to see if the w3schools example works on my site with a collapsible panel. here is what I have: Code: <script type="text/javascript"> function getXMLcontent() { if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } document.getElementById('CollapsiblePanel1').style.visibility = 'visible'; document.getElementById("CollapsiblePanelContent").innerHTML=xmlhttp.responseText; xmlhttp.open("GET","showfunction.php?fname=" + document.getElementById('functions').value, true); xmlhttp.send(); alert("showfunction.php?fname=" + document.getElementById('functions').value); } </script> the panel shows up as a thin grey line because no text is being thrown into it from the 'responsetext' property. I don't really know anything about what I'm doing. Just trying to copy and paste what the website example is. is there anything else I should know about what I'm doing, that would at least tell me why I'm not getting the data back out of the server like I should be? the 'functions' element on the page is a dropdown box, but it is not inside of a form tag. does that make a difference since I am using 'GET'?? thanks! This question hovers between PHP and JavaScript, but I think it fits here a little better. I've got a web app that does a lot of asynchronous calls to various PHP pages. I'm familiar with using an iFrame or div to hold a controller, then making forms post to that controller so you can see the output. However, I'm not doing a lot of submitting forms. Typically, I utilize the onclick event of various elements to initiate an XmlHttpRequest that jumps over to a PHP page and back. I'm looking for a way to easily debug my PHP code. Right now I'm using Firebug (on Firefox) to look at the HTTP requests. I can see the post data and response and all that, which is good. However, it requires a good amount of clicking and time to get to that data. Is there an easier way to do this? Ideally I'd love to include some sort of debug window that displays all of the PHP controller errors and things that I echo out. |