Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-31-2012, 05:20 PM   PM User | #1
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
Problems accessing xml on localhost and access to getbytagname

Hello,
I am new to javascript coding and and am trying to access an xml doc on the localhost and write its contents to a div. The xml file is not formated as a hierarchical data file unfortunately but rather as html, i.e., <table>, <tr>, <td>, etc. tags. The data I'm trying to get to is in the <td> tags - see code below. So, I'm trying too access the xml doc, "parse" the dom, get to the values in the <td> tags, and write the table of data (from the xml file) to the targetDiv. Right now, nothing is happening when I click the input button, i.e., no errors, etc., nothing happens. Thanks for any help!

Code:
<html> 
<head> 
<title>Ajax at work</title> 

<script language = "javascript">
 var XMLHttpRequestObject = false; 

var txt,x,xx,i;
 

if (window.XMLHttpRequest) {
 XMLHttpRequestObject = new XMLHttpRequest();
 
} else if (window.ActiveXObject) {
 
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
 }
 

function getData(dataSource, divID) 
{ 
if(XMLHttpRequestObject) {
 var obj = document.getElementById(divID); 
XMLHttpRequestObject.open("GET", dataSource); 

XMLHttpRequestObject.onreadystatechange = function() 
{ 
if (XMLHttpRequestObject.readyState == 4 && 
XMLHttpRequestObject.status == 200) { 

txt="<table 

border='1'><tr><th>Score</th><th>Origin</th><th>Target</th><th>Target 

Location</th><th>Purpose</th></tr>";
 

//document.write("XML document loaded into an XML DOM Object.");

 x=xmlhttp.responseXML.documentElement.getElementsByTagName("<TD>");

 
for (i=0;i<x.length;i++)

 {

 
txt=txt + "<tr>";

 xx=x[i].getElementsByTagName("<TD>");

 {
 
try

 {
 
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";

 }
 
catch (er)
 
{
 
txt=txt + "<td> </td>";
 
}
 }

 xx=x[i].getElementsByTagName("<td>");
 
{

 try
 
{

 txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
 
}
 
catch (er)
 
{

 txt=txt + "<td> </td>";
 
}

 }

 txt=txt + "</tr>";

 }

 txt=txt + "</table>";
 document.getElementById('targetDiv').innerHTML=txt;
 }
 

} 
} 

XMLHttpRequestObject.send(null); 
}
 }
 </script>
 </head> 

<body>
 

<H1>Fetching data...</H1>
 
<form>
 <input type = "button" value = "Display Message" 
onclick = "getData('http://localhost/IIQ/out_RSS_example2.xml', 'targetDiv')"> 
</form>
 
<div id="targetDiv">
 <p>The fetched data will go here.</p> 
</div> 


</body> 
</html>
mvandall is offline   Reply With Quote
Old 10-31-2012, 07:04 PM   PM User | #2
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Quote:
Originally Posted by mvandall View Post
Right now, nothing is happening when I click the input button, i.e., no errors, etc., nothing happens.
What do you mean 'no errors'? There at least two syntax errors that prevent anything working. USE THE ERROR CONSOLE.
Logic Ali is offline   Reply With Quote
Old 10-31-2012, 07:50 PM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
And at least two usage errors, as well.

We *guarantee* you *ARE* getting errors...you are simply ignoring them.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-01-2012, 04:35 PM   PM User | #4
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
First - thanks very much for the replies!!!

Ok, now using the error console and I was getting at least one syntax error - added a missing curly bracket. Now I'm getting the following error but I'm not sure why the function is null or undefined or not an object. I defined it in the head of the document, etc. The xml file which it points to is there on the localhost in the path specified, so not sure what's up.

SCRIPT5007: The value of the property 'getData' is null or undefined, not a Function object

BTW, can you recommend a good free dev environment?

Thanks!!!!
Michael
mvandall is offline   Reply With Quote
Old 11-01-2012, 04:58 PM   PM User | #5
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Show your code in its current state.
Logic Ali is offline   Reply With Quote
Old 11-01-2012, 06:16 PM   PM User | #6
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
Code:
<html> 
  <head> 
    <title>Ajax at work</title> 

    <script language = "javascript">
      var XMLHttpRequestObject = false; 

var txt,x,xx,i;


      if (window.XMLHttpRequest) {
        XMLHttpRequestObject = new XMLHttpRequest();

      } else if (window.ActiveXObject) {

        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
      }


      function getData(dataSource, divID) 
      { 
        if(XMLHttpRequestObject) {
          var obj = document.getElementById(divID); 
          XMLHttpRequestObject.open("GET", dataSource); 

          XMLHttpRequestObject.onreadystatechange = function() 
          { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) { 

			txt="<table border='1'><tr><th>Score</th><th>Origin</th><th>Target</th><th>Target Location</th><th>Purpose</th></tr>";


//document.write("XML document loaded into an XML DOM Object.");
 		
		x=xmlhttp.responseXML.documentElement.getElementsByTagName("<TD>");
    

		for (i=0;i<x.length;i++)
 
		{
      

		txt=txt + "<tr>";
      
		xx=x[i].getElementsByTagName("<TD>");
		
        {

        		try
          
			{

          		txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
		
          }

		        catch (er)

		          {

          		txt=txt + "<td> </td>";

          		}
        		}
      
			xx=x[i].getElementsByTagName("<td>");

		        {
        
			try

		          {
          			
			txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";

		          }

       			 catch (er)

         		{
          
			txt=txt + "<td> </td>";

          		}
        
		}
      
			txt=txt + "</tr>";
      
			}
    
			txt=txt + "</table>";
			document.getElementById('targetDiv').innerHTML=txt;
    }

                  
            } 
          } 

          XMLHttpRequestObject.send(null); 
        }
      }
    }
    </script>
  </head> 

  <body>


    <H1>Fetching data...</H1>

    <form>
      <input type = "button" value = "Display Message" 
        onclick = "getData('http://localhost/IIQ/out_RSS_example2.xml', 'targetDiv')"> 
    </form>

    <div id="targetDiv">
      <p>The fetched data will go here.</p> 
    </div> 


  </body> 
</html>
mvandall is offline   Reply With Quote
Old 11-01-2012, 08:42 PM   PM User | #7
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
I think it would be more important to see the XML he is trying to load.

As his code is written, it makes no sense:

First, this line:
Code:
x=xmlhttp.responseXML.documentElement.getElementsByTagName("<TD>");
will get *ALL* the <TD> elements into the collection referenced by x.

But then this line
Code:
 xx=x[i].getElementsByTagName("<TD>")
gets all the <TD> elements *INSIDE* of one of the <TD>s.

Now, I grant you that is possible.

XML such as:
Code:
<TD>
    <TD>something</TD>
</TD>
<TD>
    <TD>more stuff</TD>
</TD>
would allow that. But is that LIKELY?

I want to see the XML.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-02-2012, 03:36 PM   PM User | #8
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
Ok, yes, my code may be a little screwy, but that's why I'm here :-) And, I do really appreciate the help!

Agreed, seeing the xml is probably a good idea, so I'm pasting it below..... I think it's not a "pretty" xml file or not formated as an xml data file should be, but it wasn't for me to choose. I just have to parse it and display the data in the tables (well, actually the contents of the whole file, but I'm starting with the data in the tables). Hopefully I can convince the client that they need to format the xml as xml data, etc.

Code:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-16">
<style type="text/css">
                    body	{ font: 12px Verdana }
                    tr.rowOdd {background-color: white}
                    tr.rowEven {background-color: #f5f5f5}
                    table th,
                    table td { 
                    text-align: left;
                    border: 0px;
                    border-right:1px solid lightgrey;
                    padding: 0.2em 0.5em;
                    }
                    table th {
                    background-color: #f3f3f3;
                    border-bottom: 1px solid lightgrey;
                    }
                    
                    table td.number { 
                    text-align: right;
                    }
                    h1	{ text-align: center; background-color:#f5f5f5 }
                    h2	{ text-align: center; background-color:#f5f5f5 }
                    
                </style>
</head>
<body>
<h1 style="width: 100%;">Engine Results</h1>
<table border="0" cellpadding="3" cellspacing="0" style="width:100%">
<TR>
<TD><img src="images/out_RSS_example2.jpg" align="center"></TD>
<TD valign="top">
<h2>Query parameters</h2>
<table border="0" cellpadding="0" cellspacing="0" style="border:2px gray outset">
<TR><TD>Cincinnati</TD></TR>
<TR><TD>OIA</TD></TR>
<TR><TD>RT</TD></TR>
<TR><TD>
                        123456
                        987654
                    </TD></TR>
</table>
</TD>
<TD valign="top">
<h2>Best matches</h2>
<table id="Data" border="0" cellpadding="0" cellspacing="0" style="border:2px gray outset">
<tr>
<th>Score</th>
<th>Origin</th>
<th>Target</th>
<th>Target Location</th>
<th>Purpose</th>
</tr>
<tr class="rowOdd">
<TD class="number">150.0</TD>
<TD>Dallas</TD>
<TD>OIA</TD>
<TD>USA</TD>
<TD>BT</TD>
</tr>
<tr class="rowEven">
<TD class="number">150.0</TD>
<TD>Seatle</TD>
<TD>OIA</TD>
<TD>USA</TD>
<TD>BT</TD>
</tr>
<tr class="rowOdd">
<TD class="number">150.0</TD>
<TD>Denver</TD>
<TD>OIA</TD>
<TD>USA</TD>
<TD>BT</TD>
</tr>
<tr class="rowEven">
<TD class="number">150.0</TD>
<TD>New York</TD>
<TD>OIA</TD>
<TD>USA</TD>
<TD>PT</TD>
</tr>
<tr class="rowOdd">
<TD class="number">150.0</TD>
<TD>Chicago</TD>
<TD>OIA</TD>
<TD>USA</TD>
<TD>PT</TD>
</tr>
</table>
</TD>
</TR>
</table>
</body>
</html>
mvandall is offline   Reply With Quote
Old 11-02-2012, 07:52 PM   PM User | #9
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
You know, there may be an easier way to do this.

Since that *IS* HTML, don't even try to treat it as XML.

Instead, put a HIDDEN <iframe> on your page and load the HTML in that <iframe>.

Then you can just use HTML DOM methods in your JS code to grab the relevant data out of the <iframe>!
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-05-2012, 02:45 PM   PM User | #10
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
True it is html and good/great suggestion! However, I have a couple objectives going on - 1st is to parse the file/data, but 2nd is to access xml on remote servers and parse the xml (albeit in this case html). I need to do both, access the file on a server, and parse it. I also have other objectives on the presentation or client-side, but right now, I'd like to pretend that this is an actual xml file on a server. Eventually my customer will produce an actual xml file (and I need to know how to do this in general), hopefully sooner rather than later.

So, wondering if you (all) can still help me figure out why my code isn't finding all the <td>'s and spitting them out onto the screen in the target div? The code is supposed to create an html table of the data in that xml(html) file.

Thanks again!
Michael
mvandall is offline   Reply With Quote
Old 11-05-2012, 05:46 PM   PM User | #11
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 961
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Quote:
Originally Posted by mvandall View Post
So, wondering if you (all) can still help me figure out why my code isn't finding all the <td>'s and spitting them out onto the screen in the target div? The code is supposed to create an html table of the data in that xml(html) file.
You still need to test it on valid XML.

"some.xml"
Code:
<xml>
 <core>
  <TD class="number">150.0</TD>
  <TD>Dallas</TD>
  <TD>OIA</TD>
  <TD>USA</TD>
  <TD>BT</TD>
 </core>
</xml>
Here's a simplified example that just creates a single row of TDs:
Code:
<!DOCTYPE HTML>
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ajax</title>

<script type = "text/javascript">

function getData(dataSource, divID)
{
  var rq = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"),
      obj = document.getElementById(divID);

  obj.innerHTML = "Fetching data..." ;
      
  rq.open("GET", dataSource);

  rq.onreadystatechange = function()
  {
    var tdGroup,
        tbl = document.createElement( 'table' ),
        row,
        cell;
        
    tbl.appendChild( document.createElement( 'tbody' ).appendChild( row = document.createElement( 'tr' ) ) );     
    
    if( this.readyState == 4 && this.status == 200 )
      {
        tdGroup = rq.responseXML.getElementsByTagName( 'TD' );
        
        obj.innerHTML = '<p>'; 
 
        obj.appendChild( tbl );
               
        for( var i = 0; tdGroup[ i ]; i++ )
        {
           row.appendChild( cell = document.createElement( 'td' ) );
           cell.appendChild( document.createTextNode( tdGroup[ i ].firstChild.nodeValue ) );
           cell.style.backgroundColor = i&1 ? '#0f0' : '#0ff';
        }      
      }        
   }
    
  rq.send(null);
}
</script>
</head>

<body>
    <form>
      <input type = "button" value = "Display Message"
        onclick = "getData('some.xml', 'targetDiv')">
    </form>
    <div id="targetDiv">
      <p>The fetched data will go here.</p>
    </div>
  </body>
</html>
Logic Ali is offline   Reply With Quote
Old 11-05-2012, 07:34 PM   PM User | #12
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Also, if by "remote servers" you mean servers OTHER than the one where the HTML page is running, you can't do that with JavaScript. JavaScript only allows you to access data from the SAME DOMAIN as the page running the script.

You would need to set up a proxy server on your own domain that fetched the remote data for you. Not hard to do, but can't be done with JS.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-09-2012, 03:19 PM   PM User | #13
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
Ok, sorry for the delay.....life etc., but i tried the code you provided and unfortunately it didn't work. The console reports that it's missing a ";" but I don't see where it should be - I mean, it looks like all of the ';' are in the right place.

???

Michael

P.S. Thanks for the heads-up on accessing other servers via js!
mvandall is offline   Reply With Quote
Old 11-09-2012, 09:11 PM   PM User | #14
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
LogicAli's code in post #11 worked perfectly first time when I tried it.

Did you copy/paste it or type it in?

To get usable copyable code from this silly forum, hit the "Quote" button on post #11 and then copy from the edit window that quotes the code.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-13-2012, 05:02 PM   PM User | #15
mvandall
New to the CF scene

 
Join Date: Oct 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
mvandall is an unknown quantity at this point
Success! Got it to work! Copy and pasted from the quote/editor. I had to edit the path to the data file to: "http://localhost/IIQ/some.xml".... Why would I have to specify the specific path if the the file, some.xml, was in the same directory as the index.html?

Will this code work on my original file that isn't formatted as xml (i.e., it's just html)? (I'll try it and see.) If you think it won't work, what can I do to get my original code to read the html file - basically to do what you did with this xml file?

As always, thank you all!

Michael
mvandall is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:29 AM.


Advertisement
Log in to turn off these ads.