My jquery code is not working for changing the page with ajax

Viewed 79

I type my first code with ajax but it doesn't.Please help. It must be change the section content with inside of menu.txt when I click the menu button.But it doesn't work.

this is my html code:

<li id="navMenuButton">
              <a  href="#" onclick="$menu.txt.loadDoc();">
                <span class="glyphicon glyphicon-cutlery"></span><br class="hidden-xs"> Menu</a>
</li>
<section id="homepage">
    <div id="main-content" class="container">  
      <div class="jumbotron">
      </div>
      <div class="row">
.
.
.

and this is my js code:

$(document).ready(function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("#homepage").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "menu.txt", true);
  xhttp.send();
});
1 Answers

The .ready() handler takes a function to execute once the DOM is loaded. It has to be an anonymous function statement or the reference to an already declared named function.

About the ajax request...Since you use jQuery, I would suggest you to try the jQuery $.ajax() method.

$(document).ready(function(){ // An anonymous function to pass to the ready handler

  // A named function for the ajax request
  function loadDoc(e){
    e.preventDefault()  // to prevent the normal behavior of the anchor
  
    $.ajax({
      url: "menu.txt",  // make sure the path and filename is correct
      method: "get",  // can be omited because it is the default
      dataType: "html",
      success: function(response){
        $("#homepage").html(response) // the text response passed to the .html() method
      },
      error: function(request, status, error){
        console.log("Status",status,"\nERROR",error)  // If there is an error
      }
    })
  }
  
  // Click handler for the anchor child of #navMenuButton
  $("#navMenuButton a").click(loadDoc)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="navMenuButton">
  <a href="#">
    <span class="glyphicon glyphicon-cutlery"></span>
    <br class="hidden-xs"> Menu</a>
</li>
<section id="homepage"></section>

The demo obviously won't work here because the "menu.txt" file does not exist and because SO snippets are bloquing requests. But you can see the error callback is fired.

Related