0

I'm currently learning javascript and I'm attempting to create divs based on an xml file.

XML File - I realize the info is not correct(years).

<?xml version="1.0" encoding="UTF-8"?>
<Movies>
        <Movie>
                <Title>Independence Day</Title>
                <Year>2003</Year>
                <Rating>75</Rating>
        </Movie>
        <Movie>
                <Title>GroundHog Day</Title>
                <Year>1998</Year>
                <Rating>80</Rating>
        </Movie>

</Movies>

I'm then trying to produce an html file where I can format the divs with css.

html with JS

<html>
    <style type="text/css">
p {
    font-size: 14px;
}

div {
    border: 1px black solid;
    width: 100px;
    height: 100px;  
    position: relative;
    float: left;
}

</style>

 <body>

 <script>
 xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET","movies.xml",false);
 xmlhttp.send();
 xmlDoc=xmlhttp.responseXML; 


 var x=xmlDoc.getElementsByTagName("Movie");
 for (i=0;i<x.length;i++)
   { 
   document.write("<div><p>");
   document.write(x[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue);
   document.write("</p><p>");
   document.write(x[i].getElementsByTagName("Year")[0].childNodes[0].nodeValue);
   document.write("</p><p>");
   document.write(x[i].getElementsByTagName("Rating")[0].childNodes[0].nodeValue);
   document.write("</p></div");
   }

 </script>

 </body>
 </html>

I'm getting data back, but I'm only producing one div with the data spilling out the bottom. Why isn't this producing two divs - 1 per movie?

MVC_Future_Guru
  • 229
  • 3
  • 15

3 Answers3

3

Since you want to learn things, I'm noting some points you should consider.

The style you write looks very oldschool, you should improve the following points:

  • use JSON instead of XML. This protocol is more lightweight than XML and is much better to be processed by Javascript.

  • don't use synchronous Ajax Calls

  • don't use document write, create the elements directly and insert them afterwards.

My example does not include the ajax request, you can look at the according MDN Docu on AJAX Calls to see, how it's properly done.

// the important stuff of your async ajax call:

xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      writeYourResultToTheDocument(xhr.responseText);
    } else {
      console.error("An error occured!" + xhr.statusText);
    }
  }
};


function writeYourResultToTheDocument(response){

/* This code should is called when your request is complete */

// this is how it would look like in real:
// var movies = JSON.decode(response);
// since I don't do a real request, I take a "fake" result:
var movies =  [
        {   "Title" : "Independence Day",
            "Year": 2003,
            "Rating":75
        },
        {
            "Title":"GroundHog Day",
            "Year":1998,
            "Rating":80
        } 
    ];

 // Create Container Element for all movies
var container = document.createElement("div");

// declare every variable you use with "var" to *not* 
// create a global variable accidently
var movie,node;

// iterate over the result
for (var i = 0;i < movies.length;i++){
    //create a div for each movie
    movie = document.createElement("div");
    // insert all information
    for(el in movies[i]){
        node = document.createElement("p");
        node.innerHTML = el + " : " +movies[i][el];
        console.log(node);
        movie.appendChild(node);
    }
    container.appendChild(movie);
}
// finally, append the container to your document
document.body.appendChild(container);

}

And here how it could work: http://jsfiddle.net/xyLe4/

Christoph
  • 46,101
  • 18
  • 92
  • 121
  • 2
    Since we're enumerating little tips, here's another: use `var` so that the global namespace doesn't get [polluted](http://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted) – sushain97 Mar 27 '14 at 16:29
1

Not sure if this is a typo in your post or in your actual code, but you're missing the closing > on your last div. That very well could be what's causing the problem...

Dryden Long
  • 9,332
  • 2
  • 28
  • 42
1

Use document.createElement('div') to create the elements and append the childs to the body.

var newDiv = document.createElement('div');
document.body.appendChild(newDiv);

And a little working example: http://jsfiddle.net/NicoO/FKHb6/

Here is the same example with some Text content:

var Text = "Hello fine sir!"
var newDiv = document.createElement('div'); 
newDiv.appendChild(document.createTextNode(Text));
document.body.appendChild(newDiv);

See this in Action: http://jsfiddle.net/NicoO/FKHb6/1/

Nico O
  • 12,361
  • 7
  • 41
  • 65