user1688011
user1688011

Reputation: 1

Load external pages using jquery

I'm trying to use jQuery to load external pages into the current page without the user seeing the page load.

When I call the page 'info.php' it is loaded into the #content div. That's what the script is supposed to do. The problem is that in the main page, which contains the script and the #content div, I already have some code that I want it to be executed when someone visits the page and not to be called from any external page. This is working but when I click on one of the links in the menu, I can't go back to the initial content.

Here is an except of my code:

<script>
$(function() {
   $('#nav a').click(function() {
    var page = $(this).attr('href');
    $('#content').load(page + '.php');
    return false;
    });
});
</script>

<ul id="nav">
<li><a href="#">Page1</a></li>
<li><a href="about">About</a></li>
<li><a href="contact">Contact</a></li>
<li><a href="info">Info</a></li>
</ul>

<div id="content">
Here I have some code that I wanted to be attributed to the "Page1"
</div>

Upvotes: 0

Views: 1089

Answers (2)

webdeveloper
webdeveloper

Reputation: 17288

Here is example:

$(function()
{
   var content = $('#content');

   $('#nav a').click(function(e) {
       e.preventDefault();
       var page = $(this).attr('href');

       content.children().hide();
       var pageContent = content.find("#" + page);
       if(pageContent.length > 0)
       {
           pageContent.show();
       }
       else // put ajax here
       {
           content.append($('<div>').attr('id', page).text('New page ' + page));
       }
   });
});

Demo: jsfiddle.net/3jLjw/

Upvotes: 0

esandrkwn
esandrkwn

Reputation: 399

I'm not very familiar with load(), but in this case, I think you should be using ajax to load the page without refresh.

var page = $(this).attr('href');
$.ajax({
  url: page + '.php',
  success: function(data)
  {
     $('#content').html(data);
  }
})

EDIT: with you said "when I click on one of the links in the menu, I can't go back to the initial content", did you mean you have some code within the div #content and onclick you've overwritten its contents?

Upvotes: 0

Related Questions