0

Im trying to print the Book title , price and date from in xml file with ajax using javascript. I spend almost two days on it and watched some video on youtube to figure it out i could not .I do not know where im doing wrong if You could help me with it you making my day .Thank you .

$(document).ready(function() {
    $("#find").click(function() {
      var book = $("#book").val();
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.status == 200) {
          document.getElementById('forPrice').innerHTML = 'Test1';
          var i;
          var xmlDoc = xhttp.responseXML;
          var x = xmlDoc.getElementsByTagName("book");
          for (i = 0; i < x.length; i++) {
            catalog + = xmlDoc[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
          document.getElementsById("#forPrice").innerHTML(catalog);
          xmlDoc[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
        document.getElementsById("#forBookInformation").innerHTML(catalog);
        xmlDoc[i].getElementsByTagName("data")[0].childNodes[0].nodeValue);
      document.getElementsById("#forPublishDate").innerHTML(catalog);

    });
  }
};
xhttp.open("POST", "books.xml", true);
xhttp.send();

})
})
<?xml version="1.0"?>
<catalog>
   <book>
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <price>44.95</price>
      <date>2000-10-01</date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <price>5.95</price>
      <date>2000-12-16</date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book>
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <price>5.95</price>
      <date>2001-03-10</date>
      <description>In post-apocalypse England, the mysterious 
      agent known only as Oberon helps to create a new life 
      for the inhabitants of London. Sequel to Maeve 
      Ascendant.</description>
   </book>
   <book>
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <price>4.95</price>
      <date>2000-11-02</date>
      <description>A deep sea diver finds true love twenty 
      thousand leagues beneath the sea.</description>
   </book>
   <book>
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <price>4.95</price>
      <date>2002-10-01</date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
   </book>
</catalog>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Books</title>
  <style type="text/css">
    table,
    td {
      border: 1px solid black;
    }
  </style>
  <script src="jquery-1.11.2.js"></script>

  <script src="p3.js"></script>
</head>

<body>
  <h1>Books</h1>

  <h2>Book Price</h2>
  <form action="" method="post">
    <select name="book" id="book">
      <option value="XML Developer's Guide">XML Developer's Guide</option>
      <option value="Midnight Rain">Midnight Rain</option>
      <option value="Oberon's Legacy">Oberon's Legacy</option>
      <option value="Splish Splash">Splish Splash</option>
      <option value="Creepy Crawlies">Creepy Crawlies</option>
    </select>
    Select a book to see the price
    <br>
    <br>
    <input type="button" id="find" value="Find!">
  </form>
  <div id="forPrice"></div>

  <h2>Author Names and Book Titles</h2>
  <div id="forBookInformation"></div>

  <h2>Book Publish Date</h2> 
  <div id="forPublishDate"></div>



  <body>

</html>

ajax using javascript. I spend almost two days on it and watched some video on youtube to figure it out i could not .I do not know where im doing wrong if You could help me with it you making my day .Thank you .

2
  • catalog + = syntax error, unexpected token = Commented May 8, 2016 at 16:25
  • Rollback explanation: Your question is unanswerable (and the helpful answers your received make little sense) without the code you've deleted in your last edit, so I've rolled back your change. Please use question editing only for clarifications and improvements to your question. Thank you. Commented May 8, 2016 at 19:04

2 Answers 2

1

There are many things wrong with your code. Let me explain where and what:

  • I changed "POST" to "GET" xhttp.open("GET", "books.xml", true);
  • document.getElementsById is wrong, since there is only one id, it should be: document.getElementById
  • had you use jQuery the syntax would be $('#forPrice') but since you use native JS, you must omit #, i.e. document.getElementById('forPrice') -> note the lack of #
  • since you use native JS (and not jQuery), innerHTML is a property and you need to use it as such (i.e. not .innerHTML('text') but .innerHTML = 'text' )
  • using just one variable in concatenating it will just add text to one value.. so I changed from catalog to specific values (you can revert this change if you feel like it).
  • there were a lot of ) that are not allowed.

All in all, what I changed is not totally correct, but at least the data gets loaded. However, since you do not check what has been selected from the select-option element, the data gets overwritten.

Hope this helps you get going on the right direction!

Here's the link to the working example. http://plnkr.co/edit/4TrjfX4LI8234lFVwIyU?p=info

Sign up to request clarification or add additional context in comments.

7 Comments

thank you my Friend . you showed there is still good people in this world :)
No problem! If you have any questions, just ask. And please accept my answer if you feel that I've helped you enough. Thank you!
Yes of course, no problem. Basically, you need to "mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot below)", taken from here: meta.stackexchange.com/questions/5234/…
Thank you done ...one last question when im running your code and i chose a book from the list it print but when im i chose another book it does not change .Can you help me with it plz
Yes, that is because you did not check if book (value from the select/option element) equals the current item in for sentence. Of course, this could be done more elegantly, but for the sake of this example, I changed it for you. Here you go: plnkr.co/edit/S6jQ9iVPw8nP6nugGnsO?p=preview
|
0

I am assuming that you know ajax very well.

  var data = "<?xml version='1.0'?> <catalog> <book> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <price>44.95</price> <date>2000-10-01</date> <description>An in-depth look at creating applications with XML.</description> </book> <book> <author>Ralls, Kim</author> <title>Midnight Rain</title> <price>5.95</price> <date>2000-12-16</date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book> <author>Corets, Eva</author> <title>Oberon's Legacy</title> <price>5.95</price> <date>2001-03-10</date> <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description> </book> <book> <author>Thurman, Paula</author> <title>Splish Splash</title> <price>4.95</price> <date>2000-11-02</date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description> </book> <book> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <price>4.95</price> <date>2002-10-01</date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects.</description> </book> </catalog>";

$(document).ready(function() {
  var getBookByTitle = function(title){
        var bookElement = undefined;
        var xmlDoc = $.parseXML( data ),
        xml = $(xmlDoc),
        catalog = xml.find( "catalog" );
        $.each(catalog.find('book'), function(i, book){
          if($(book).find("title").text() == title){
            bookElement = {};
            bookElement.author = $(book).find("author").text();
            bookElement.title = $(book).find("title").text();
            bookElement.price = $(book).find("price").text();
            bookElement.date = $(book).find("date").text();
          }
          
        });

        return bookElement;
      };

    $("#find").click(function() {
      var searchBook = $("#book").val();
      var bookElement = getBookByTitle(searchBook);
      $("#forPrice").text(bookElement.price);
      $("#forBookInformation").html("<i>"+ bookElement.author +","+bookElement.title +"</i>");
      $("#forPublishDate").text(bookElement.date);
    });
  
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<h1>Books</h1>

  <h2>Book Price</h2>
  <form action="" method="post">
    <select name="book" id="book">
      <option value="XML Developer's Guide">XML Developer's Guide</option>
      <option value="Midnight Rain">Midnight Rain</option>
      <option value="Oberon's Legacy">Oberon's Legacy</option>
      <option value="Splish Splash">Splish Splash</option>
      <option value="Creepy Crawlies">Creepy Crawlies</option>
    </select>
    Select a book to see the price
    <br>
    <br>
    <input type="button" id="find" value="Find!">
  </form>
  <div id="forPrice"></div>

  <h2>Author Names and Book Titles</h2>
  <div id="forBookInformation"></div>

  <h2>Book Publish Date</h2> 
  <div id="forPublishDate"></div>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.