dynamic content load in jquery ajax

- 1 answer

Ad

this is my first jquery code.Here i am trying to do a content loading mechanism using jquery ajax. It supposed to load content in a container div.But it is navigating me to a whole new page.I want that the 'a' tag does not navigate me to another page.What i am doing wrong here ?How i can achieve that?

<html>

<body>
<ul>
<li><a href='about.html'>about</a></li>
<li><a href='faq.html'>faq</a></li>
</ul>
<div id='content'></div>
<script src='c/xampp/htdocs/practice/jquery/jquery.js'></script>
<script>
$('a').click(function(){
       var page=$(this).attr('href');
       $('#content').load(page);
       return false;
});
</script>
</body>
</html>
Ad

Answer

Ad

You are clicking on a link which should take you to the page before you do anything. Use event.preventDefault() to prevent this.

$('a').click(function(event){
       event.preventDefault();
       var page=$(this).attr('href');
       $('#content').load(page);
       return false;
});

Also you should include jQuery using your localhost url : (I guess you are using proper link for the page?)

 <script src='http://localhost/practice/jquery/jquery.js'></script>

Remember, type="text/javascript" definition is not necessary in html5. But you didn't use the html5 doctype definition. Use this at the top of everything in the page.

<!DOCTYPE html>
Ad
source: stackoverflow.com
Ad