JavaScript - Ajax Xmlhttprequest Responsetext Returns Undefined But...
AJAX 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>'; Similar TutorialsI 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(""); } 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; } 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. Edit: Nevermind
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! 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 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? Edit: digged out some old code , added blue lines, explanation ? Code: comments = new Comments("some text") function Comments(jsp) { this.jsp = jsp; var that = this; this.save = function(obj) { alert(this.jsp);// pops out 'some text' .... ///call ajax ... catch response in catch_save } this.catch_save = function() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { alert(this.jsp);// pops out undefined alert(that.jsp);// pops out 'some text' } } } how come that there is undefined ? 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> 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'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'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. I'm trying to create a script that will call a flickr rest method and output its XML. I have written the following code, but it seems to not work. I am stumped, and was wondering what I am doing wrong. I have uploaded my code to http://www.sfu.ca/~jca41/stuph/blahh/example.html Code: function foo() { //var url = "http://flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=aa9b622e629e51d3fcda1f967c429237&photo_id=6174355034"; alert(loadXMLDoc(url)); } function loadXMLDoc(dname) { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",dname,false); xhttp.send(""); return xhttp.responseText; } </script> 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. Hi, I am trying to create a script that would output two variables - X Controllers and Y Pilots. Basically, I would need to capture the contents of the following webpage and extract those two numbers from the second line of text. http://66.109.25.244/ I think this may involve XMLHttpRequest but I am not sure. If anyone can help me do this, I would greatly appreciate it. Thanks in advance! Hi, because i need to get rid off Code: <iframe src="my.php"> in my html page, i have decided to replace it with javascript function which will get data from the server and will insert it into div section.But i dont know how can i obtain html page from my.php script... I know there is function XMLHttpRequest, but does it use current session from the browser ( my.php is protected - it does check the $_SESSION variable ) ? And does work this function in Mozilla ? Hi There, Can anyone explain why the following XMLHttpRequest.open call fails on IE browsers, but works fine in Firefox and Chrome? Code: <html> <head> </head> <script type="text/javascript"> if( window.XMLHttpRequest ) { xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","test.xml",false); // I show an "access is denied error in IE" xhttp.send(""); document.write( xhttp.responseXML.getElementsByTagName("simple")[0].childNodes[0].nodeValue ); </script> <body> </body> </html> The "text.xml" file resides in the same location (local HDD folder on the pc this is running on) as the html page. And the contents of "test.xml" are shown below: Code: <simple> Hello </simple> Obviously its just a very simple example that should just display "Hello" when loaded, but it fails to work in IE. |