Question

So I am new to jQuery and I'm trying to set up an html page that has tabs. Each tab should show a different html page as follows:

<div id="tabs">
   <a href="page1.html"><div class="tabdiv tabActive">Page1</div></a>
   <a href="page2.html"><div class="tabdiv">Page2</div></a>
   <a href="page3.html"><div class="tabdiv">Page3</div> </a>
   <a href="page4.html"><div class="tabdiv">Page4</div></a>
</div>
<div class="tabscontent" id="ajax-content">
    Default text
</div>

So what I want is that when I click on page 1, page1.html will be loaded up in div.tabscontent. This is the jQuery code that I have.

$(document).ready(function() {
    $("div#tabs a").click(function() {
                alert(this.href);
        $("#ajax-content").empty().append("Loading");
        $("div#tabs div.tabdiv").removeClass('tabActive');
        $(this).children('div.tabdiv').addClass('tabActive');

        $.ajax({ 
            url: this.href, 
            success: function(html) {
                $("#ajax-content").empty().append(html);
                alert("Success!");},
            error: function() {
                $("#ajax-content").empty().append("Didn't work");}
            });
    return false;
    });
});

Note: 1) I have the latest jquery attached 2) I the page1.html, page2.html, etc are in the same folder as the above html file. 3) I am working locally and have tried google-chrome, firefox, and opera and they all had tabs that showed "Didn't work". Even when I reference http://www.facebook.com in the url it doesn't work. Please help me.

I put the alert in there to see if the href works and it does work. For example for page1 tab it returns `file:///u/b/user/Desktop/ajaxdemo/Page1.html'

Was it helpful?

Solution

In your case, it does not work because you're trying to access a file from user computer. It poses security risks because if javascript is able to access local files, javascript is able to steal files from client machine.

Even when I reference http://www.facebook.com in the url it doesn't work

The reason for this is: AJAX requests are subject to the same-origin policy. Facebook is on another domain, that's why it does not work.

One more thing to keep in mind, some browsers think absolute URLs are cross-domain requests even if it's in the same domain, only relative Urls work, so avoid using absolute Urls.

To fix your issues, try deploying on a server and use relative URLs instead of absolute URLs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top