0

Javascript/Ajax learner here!

I'm trying to use Ajax to load a page in a div when I click on the menu items in the navbar. I encounter several problems:

  1. When I click the item "past" in the navbar for instance, I get the following error message in the console that refers to page I'm trying to load: "XML Parsing Error: mismatched tag. Expected: ". I can't see anything in the "past" page except for the closing head tag so I assume there's a problem in my Ajax code.

  2. The page loads anyway, but the display of the navbar changes completely (for whatever reason).

Regarding problem 1, someone in my class suggested it might be related to an identified "response" type. But I didn't find anything that works.

Any help regarding what I have to look up is welcome. You don't have to solve my broken code. :-)

Thanks!

<body>

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="index.html">EMILIE 1, 2, 3!</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a id="past" href="#" onclick="display1()">Past</a></li>
      <li class="active"><a id="present" href="#" onclick="display2()">Present</a></li>
      <li class="active"><a id="future" href="#" onclick="display3()">Future</a></li>
    </ul>
  </div>
</nav>

<div id="container-fluid"></div>

<script>

// Past
function display1() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("container-fluid").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "past.html", true);
  xhttp.send();
}

</script>

</body>
Meulymooh
  • 33
  • 3
  • 2
    "XML Parsing Error: mismatched tag. Expected: " means that your XML is invalid. Start there and fix the that error. – some Apr 30 '19 at 14:52
  • I tested your code but I couldn't reproduce the `XML Parsing Error`. It would be more helpful if you show the `past.html` content. As for the changing navbar display - maybe in `past.html` there are global CSS properties that change it? – Christoph Apr 30 '19 at 15:04
  • You should use your console's network tab to check what the response is you're getting. My guess is that that isnt what you want/incorrect html – Martijn Apr 30 '19 at 15:10

1 Answers1

0

If you try to fetch html file in local, you need setup security for browser allow enable CORS.

Disable same origin policy in Chrome

You should use a web server to open file. I host your code to sample in free host. It worked

https://viethien.000webhostapp.com/xmlget.html

Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48