Matthew Smith
Matthew Smith

Reputation: 11

Displaying an image using AJAX from XML

I am learning AJAX and I am trying to call an image from an XML contact and display it in a table.

The XML contact is the following:

<contact>
  <name>xxx xxx</name>
  <post>xxx xxx</post>
  <company>xxx</company>
  <address>xxx</address>

  <telephone>xxx</telephone>
  <mobile>xxx</mobile>

  <email>xx@xxx</email>
  <photo>img/xxx.jpg</photo>
</contact>

And the Ajax that I am calling this from is the following:

function myFunction(xml) {
        var i;
        var xmlDoc = xml.responseXML;
        var table = "<tr><th>Name</th><th>Post</th><th>Company</th><th>Address</th><th>Telephone</th><th>Mobile</th><th>Email</th><th>Photo</th></tr>";
        var x = xmlDoc.getElementsByTagName("contact");
        for (i = 0; i < x.length; i++) {
          table += "<tr><td>" +
            x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("post")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("company")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("address")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("telephone")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("mobile")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue +
            "</td><td>" + 
            x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
            "</td></tr>";
        }

Currently the table displays with Photo tag but just the text "img/xxx.jpg" instead I want it to display the actual image.

Upvotes: 0

Views: 420

Answers (1)

freefaller
freefaller

Reputation: 19963

You need to implement the <img> tag, as otherwise (as you've found) all you're doing is displaying the path.

Try replacing the following lines at the end...

        "</td><td>" + 
        x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
        "</td></tr>";

With...

        "</td><td><img src='" + 
        x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
        "'/></td></tr>";

Upvotes: 1

Related Questions