2

I'm interested in Ajax and dynamically loading content into a div. I have been using jQuery for a few months now, but I am new to Ajax. I found this downloadable tutorial online: here that worked fine, but when I downloaded it and tested it locally, the content does not dynamically load. Do the webpages need to be live in order to dynamically load the content? If that's true, how do you test ajax? I've used XAMPP for dynamically loading PHP content, but have not tried with Ajax. here bellow is the simple jquery used to load the content:

$(document).ready(function(){
    $('a').click(function(e){
    e.preventDefault();
    $("#dynamic").load($(this).attr('href'));
    });
});

Any thoughts leading me in the right direction would be helpful. Thanks!

2 Answers2

0

here is the working code, change load to html;

$(document).ready(function(){
        $('a').click(function(e){
           e.preventDefault();
           $("#dynamic").html($(this).attr('href'));
        });
 });

and here is the plunker

Safi
  • 1,112
  • 7
  • 9
  • This will just load the text from the `href` attribute of the `a` tag into the div. She wants the content returned by the link loaded into the div. – Michael Hornfeck Feb 25 '15 at 18:25
  • Yes, Michael is correct. I'm sure I can get it to work.. but my question is why is the *exact* file working on the live demo, but when I download it and run it locally, it fails to pull in the new content? – Chelsea Covey Feb 25 '15 at 18:33
0

For ajax requests, you must be running the page within the context of a web server, as explained in this question: "Cross origin requests are only supported for HTTP." error when loading a local file. If you download the example from your original post and try to open the index.html page in a browser from your file system, you should see errors in the JavaScript console like this:

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

So yes, to answer your original question, the page must be "live" in the sense that it is hosted in a web server. You can test by running a local web server on your development machine and using that to serve up the page.

Community
  • 1
  • 1
Michael Hornfeck
  • 1,242
  • 1
  • 16
  • 33
  • Excellent, Michael! It works very well now. If I could up-vote your comment, I would, however I am too new. Thank you! :) – Chelsea Covey Feb 25 '15 at 19:28
  • Welcome to SO and glad I could help! You can mark my answer as the accepted answer if it solved your problem (even if you can't upvote yet) – Michael Hornfeck Feb 25 '15 at 19:34