0

I am trying to use Jquery to load html code into another html file, using Jquery's the .load() method.

I have tried using an absolute path to access the file but I am still getting the same error. I have also tried navigating to absolute path and the file and it will open with no problem in a browser so it dose not appear to be an accesses issue. I have also mapped to the latest version of jQuery instead of my local version.

The error response is unidentified which is making this problem harder to solve:

Updated Code: made changes to code from user recomendations.

Main HTML Page

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    <script type="text/javascript">
        jQuery(document).ready(function(){
            jQuery("#test").load("/menu.html", function(response, status) {

        if(status === 'error') {
            alert("Failed to load menu.html");
        }
        else {
            alert("Success!");
        }    
    });
});
</script> 
</head>

</head>

<body>
    <div id="test"></div> 
</body>

Loading HTML Page



                <ul>
                   <li><a href="index.html">Home</a></li>
                    <li>
                        <a href="article.html">Article</a>
                        <div class="uk-navbar-dropdown">
                            <ul class="uk-nav uk-navbar-dropdown-nav">
                                <li><a href="article.html">Scrollspy</a></li>
                                <li><a href="article-narrow.html">Narrow</a></li>
                            </ul>
                        </div>
                    </li>
                    <li><a href="faq.html">Faq</a></li>
                    <li><a href="contact.html">Contact</a></li>
                    <li><a href="components.html">Components</a></li>
                </ul>


If any one has any input or has run into a similar error please let me know.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65

2 Answers2

2

Looks like there are a few areas that could be causing problems - consider the following adjustments to your code:

Loading HTML Page

<!-- <div id="menu"> Remove div with menu id -->

    <ul>    <!-- Add opening ul tag -->
        <li><a href="index.html">Home</a></li>
        <li>
            <a href="article.html">Article</a>
            <div class="uk-navbar-dropdown">
                <ul class="uk-nav uk-navbar-dropdown-nav">
                    <li><a href="article.html">Scrollspy</a></li>
                    <li><a href="article-narrow.html">Narrow</a></li>
                </ul>
            </div>
        </li>
        <li><a href="faq.html">Faq</a></li>
        <li><a href="contact.html">Contact</a></li>
        <li><a href="components.html">Components</a></li>
    </ul>


<!-- </div> Remove extra div -->

Main HTML Page

In the script on your main HTML page, consider extending the load() callback to display an error if the request fails:

jQuery(document).ready(function(){
    jQuery("#menu").load("menu.html", function(response, status) {
        /* Optional, but consider revising this function to alert on error */
        if(status === 'error') {
            alert("Failed to load menu.html");
        }
        else {
            alert("Success!");
        }    
    });
});

In the case that an error does occur during the load() callback, you should check to ensure that menu.html is accessible at the specified (relative) location.

In most cases, this can be done directly in the browser by navigating to the URL of that HTML file and verifying that the HTML response is as expected.

If your menu.html file is located at the root of your server (ie yourserver.com/menu.html) then consider revising your script to fetch the menu.htm via an absolute path by adding the forward slash prefix /menu.html:

jQuery("#menu").load("/menu.html", function(response, status) {
    ....
});

Update

Alternatively, you might want to consider this approach based on the ajax() method:

jQuery(function() {
    jQuery.ajax({
        url: '/menu.html',
        dataType: 'html',
        success: function(data) {
            $('#menu').html(data);
        },
        error: function(xhr, error){
            alert('error. see console for details');
            console.error(error);
        }
    });
});

Update

Also, ensure that the content for your website/app is served from a server rather than from your file system. There are a number of ways to set up a server to achieve that - if you're using a chrome-based browser then an easy way to setup a local server on your development machine would be with this chrome extension:

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

Once installed, you can configure the extension to serve content from a directory on your development machine via a locally hosted server. At that point you'd access your website via http://localhost:[SOME_PORT]/ rather that via file:///C:/data/. Accessing your website via localhost should resolve the problem for you.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Thank you Dacre Denny I have made the changes you recommended still running into the data in the menu.html file not populating. I am able to access the menu page with absolute path and have updated the code with absolute path but I am getting "Failed to load menu.html". I have also updated the jQuery to the latest version. – William Griffiths Jun 25 '19 at 20:32
  • @WilliamGriffiths very strange - I've just added an update to my answer. Does that approach help? – Dacre Denny Jun 25 '19 at 22:40
  • Thanks for the response I think it might be a global policy or something. Error: Access to XMLHttpRequest at 'file:///C:/data/menu.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. – William Griffiths Jun 26 '19 at 17:26
  • https://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht – William Griffiths Jun 26 '19 at 20:24
  • Ah yes, in general you need to serve content (ie menu.html) from a webserver, rather that from your filesystem. I'll update my answer with details on that – Dacre Denny Jun 26 '19 at 21:25
  • Thank you for all the help. – William Griffiths Jun 26 '19 at 21:43
  • @WilliamGriffiths you're welcome - just published that update :) – Dacre Denny Jun 26 '19 at 22:19
0

In my case, it turned out that the load was failing because there were no results returned from the selector. In terms of this example, $('#test') was returning an empty result set, so the load wasn't being called. So double check that you don't have a typo, either in the selector or the <div id="test"> that makes them not match.

Obviously, this wouldn't explain the OP's problem here, given the MCVE. But others finding this question under similar circumstances may want to go through that extra debugging step.

Symptoms:

  1. The load wasn't called at all in the Networking tab of Developer Tools.
  2. When doing console.log('%o', this) in the jQuery, the length property of the prototype was 0. That meant that my version of $('#test') was returning 0 results. Once I realized that, debugging was simple. The hard part was getting to that question (why), thus this post.
mdfst13
  • 850
  • 8
  • 18