Very new to all this, so please bear with me and use simple answers!
I am trying to dynamically populate a drop down box (theSecondBox), with a list of items which is dependent on the selection made in another drop down box (theCriteria).
I have been able to do an AJAX request and am getting an XML document back.
So far my script looks like this:-
<script type="text/javascript">
var xmlHttp;
function triggerAction(){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
criteria = document.getElementById("theCriteria").value;
xmlHttp.open("GET","MyURL?criteria=" + criteria, true);
xmlHttp.send(null);
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
parseResults();}
}
}
This returns an XML document to me that looks like this :-
<list>
<string>FirstDropDownItem</string>
<string>SecondDropDownItem</string>
<string>ThirdDropDownItem</string>
</list>
So, I'm trying to populate my second drop down box with these items, using something like ...
function parseResults(){
var results
var selectTag
results = xmlHttp.responseXML;
selectTag = document.getElementById("theSecondBox");
...and this is where I need a few 'simple' pointers.
How do I populate the secondBox with the items returned in the XML document? Everything I've tried so far (and I won't reproduce it to save my embarrassment!) just gives me nulls.
Apologies for the simple question, but as I said, I'm not a programmer by any means, so any pointers to either a solution, or a good tutorial which will help to educate me would be much appreciated.
w3schools is not a good source but this one time pls take a look
at (that "if" for IE5 is absolete now):
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Frankly document.getElementById("myDiv").innerHTML=xmlhttp.responseText
is what you need.
Just before that you can just replace "list" with "ul" and string with "li".
It would be better to change xml in backend but if you can't give str.replace a try...
var new_text = text.replace(/want/g, "dont want");
Related
I am trying to read a XML file to an object using JavaScript to ultimately parse it for information and transform the data in it.
The XML file is well formed (and in the same domain), I pasted it to several validators and all came back without errors, so this shouldn't be the source of the error.
I am trying to access the file via ajax / xmlHttpRequest. Here's a code snippet of the relevant part:
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
//alert(xmlHttp.responseText);
var xmlData = xmlHttp.responseXML;
var txt="";
var x=xmlData.getElementsByTagName("rs:data");
alert(x.length);
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
}
}
xmlHttp.send();
}
Now the problem is that the variable "x" always comes back empty (length = 0). When I alert the responseText however, I can see the whole xml file in the alert message, which seems rather strange to me.
The xml file basically looks like this:
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
<s:ElementType name='row' content='eltOnly' rs:CommandTimeout='30'>
<s:AttributeType name='ows_Art' rs:name='Art' rs:number='1'>
<s:datatype dt:type='string' dt:maxLength='512' />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row [...] />
</rs:data>
</xml>
What I want is all the data stored under the node and from what I could learn
var x=xmlData.getElementsByTagName("rs:data");
should do exactly that. The only reason I can think of is that .responseXML comes back empty, however, there is no definite way to check, because if I alert(xmlHttp.reponseXML) it just tells me, that an object is returned, but not the contents of it...
Does anyone have an idea why this whole thing doesn't work? What I find most confusing is, that the .responseText works fine...
rs:data is not the tag name. The tag name is data in the urn:schemas-microsoft-com:rowset namespace (as specified by xmlns:rs='urn:schemas-microsoft-com:rowset').
You should use a namespace-aware DOM method.
var x = xmlData.getElementsByTagNameNS("urn:schemas-microsoft-com:rowset", "data");
I think I have a very simple question, but I couldn't find a solution.
So what I want is to load a DIV content via HTML. The problem is that it is not just a text, but also an image. The ajax call returns the HTML code, but this is displayed in the DIV as HTML and is not executed. Difficult to explain, but obvious from the example...
The AJAX call returns the string:
<img src="/images/weather/1.png" width="80px"><br>3.3 °C
The problem is obvious. Instead of an image and the 3.3°C in the div, I get the actual code, so instead of the image I see img src=....
I know that i need to somehow decode the HTML, but I have no clue how to do this and would very much appreciate any help.
My Javascript code is:
var xmlhttp;
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) {
newtext = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "message_ajax.php", true);
xmlhttp.send();
$('#text').fadeOut(function () {
$(this).text(newtext).fadeIn();
})
Are you looking for something like this ?
https://api.jquery.com/load/
Where you can just load HTML into a DIV using ajax. Seems to be what you're asking...
$( "#result" ).load( "ajax/test.html" );
Where your ajax/test.html file contains
<img src="/images/weather/1.png" width="80px">
Edited... to be more specific. This is using jQuery.
You should use $(this).html(newtext) instead of $(this).text(newtext).
They are quite different. .text() will "escape" your HTML and insert it as simply text. Or as the documentation states:
We need to be aware that this method escapes the string provided as
necessary so that it will render correctly in HTML. To do so, it calls
the DOM method .createTextNode(), does not interpret the string as
HTML.
You should always read the documentation first.
If you are already using jQuery, you could use it's AJAX methods which make your life much easier.
document.getElementById("divId").innerHTML = "<img ..........";
OR
$("#divId").html("<img ..........");
I am working on a little website idea, and I am not very great at any of this. I basically have an HTML quiz that will prompt the user with questions that I defined in an XML.
window.onload = function xml()
{
// get form from HTML
var form = document.getElementById("form");
// get XML document
if (window.XMLHttpRequest)
{
var xmlhttp = new XMLHttpRequest();
}
// open XML
xmlhttp.open("GET", "questions.xml", false);
xmlhttp.send(null);
// initialize elements for do document, questions, and details
var xmlDoc = xmlhttp.responseXML;
var question = xmlDoc.getElementsByTagName("question");
On the line above, I get an error saying "Cannot call method 'getElementsByTagName' of null". The strange thing, however, is that I only get said error if the XML file has multiple "question" tags. If I only have one "question" tag in my XML, the whole function works perfectly. So I am wondering what is going on in this case, and why it won't work for me.
(the rest of the code below shows where I begin to go with the function)
var qXML = xmlDoc.getElementsByTagName("q");
// write values into HTML for each question
for ( i = 0 ; i < question.length ; i++ )
{
// qBlock div for question
var div = document.createElement('div');
div.className = "qBlock";
This code continues for a while to get all fields in the HTML. In total, this block of code in the loop works all the way throughout, unless there are multiple "question" elements.
Thank you so much to anyone who can help / teach me on any of this. Also feel free to tell me if I am doing anything else incorrectly. I am open to any criticism.
While I can't be sure this is the problem without seeing your questions.xml file, you may have multiple root elements. For example:
<?xml version="1.0"?>
<question>...</question>
<question>...</question>
XML does not allow that, and it will fail to parse. Wrap them up in one root element:
<?xml version="1.0"?>
<questions>
<question>...</question>
<question>...</question>
</questions>
I've been trying to learn how to read a text file locally using JavaScript and Ajax. I've been looking on some tutorials online, and have followed them, but no matter what I do I cannot get my text to display what is in the .txt file.
function loadDoc(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
xmlhttp.open("GET","names.txt",true);
allText = xmlhttp.responseText;
lines = xmlhttp.responseText.split("\n");
}
}
xmlhttp.send(null);
document.getElementById("myDiv").innerHTML=allText;
}
I think this is meant to change the div I have (id "myDiv") to read what is in the text file, but it does not seem to do this, no matter what I try. Any help would be appreciated - I'm still new to JavaScript and Ajax.
Use Firebug or Chrome's developer tools to make sure that the AJAX call is returning the correct text.
Is names.txt in the same directory as the HTML page?
I'm writing a MacOs widget that have to explain the bus arrive retrive info from a website like this:
http://www.5t.torino.it/5t/it/trasporto/arrivi-fermata.jsp
i have to make a Get request and parse the response.. i try with:
var xmlHttp = null;
var theUrl = "http://m.gtt.to.it/m/it/arrivi.jsp?n=876";
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET",theUrl,false);
xmlHttp.send( null );
xmlDoc=xmlHttp.responseXML;
but i don't know the structure of document how i can do to navigate it?
but i don't know the structure of document how i can do to navigate it?
You either walk the tree and poke at the note type and node name of the nodes in it, or you examine the XML document manually in order to learn the structure.
It is better to make your Ajax call asynchronous imo by doing:
xmlhttp.open("GET", theUrl, true);
This will prevent your users from interfering an annoying "blocked" period on your website.
If you do so you have to add a onreadystatechange handler so you can parse the incoming data there and display the data you want to display.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status == 200) {
var content = xmlhttp.responseText;
//Parse your content here...
}
}
Clearly you have to know what data you are retrieving to be able to parse it. But for that you can just analyze the responseText and find the elements that always contain your data. Then simply retrieve the values from those <html> tags and display it accordingly.
For instance if you want to retrieve the data in a <label> with id set to arrival-time do:
content.getElementById('arrival-time').innerHTML;