Update:
I did get this working, here is the new javascript:
$(document).ready(function() {
$('a').click( function(e) {
$v = $(this).attr("class");
$targetID = ' #' + $v;
$path = $(this).attr('href') + $targetID;
$('#' + $v).load($path);
e.preventDefault();
});
What happened was that I wasn’t realizing $path was already taking into account what I was searching for, #CLASS-NAME. I had it set up to search for #class-name inside of #class-name. Thanks for your help!
Original Post:
I’m trying to teach myself how to better take advantage of ajax with jQuery, so I’m updating my portfolio to update content dynamically. This test simplifies the process, but for this case I have 3 html pages:
home.php
about.php
contact.php
with identical markup, but only their respective div containing content:
<div id="links">
<a href="../ajax/home.php" class="home">Home</a>
<a href="../ajax/about.php" class="about">about</a>
<a href="../ajax/contact.php" class="contact">contact</a>
</div>
<div id="content">
<div id="home">
<p>Home</p>
</div>
<div id="about">
</div>
<div id="contact">
</div>
</div>
So home.php contains a paragraph in #home that says ‘home’. Trying to keep it simple and boring.
Here is the javascript involved:
$(document).ready(function() {
$('a').click( function(e) {
$v = $(this).attr("class"); //pulls the name of the associated link
$targetID = ' #' + $v;
$path = $(this).attr('href') + $targetID; //generates the path that ajax is loading: "../folder/FILE-NAME/.php #DIV-NAME"
if ($('#', $v).text() == '') { //Checks whether content exists in that div already
$('#', $v).load($path + ' ' + $targetID); //Is SUPPOSED to pull content from the div on one page into its corresponding div on the current page - This is where the script is breaking
}
else {
alert($v + " isn't empty!");
}
e.preventDefault(); //prevents normal link behavior
});
});
The part where the script is breaking is of course the part I’m just learning to use – the ajax request to load the content from one div on a different page and putting it into the right div on the current page.
Can someone point out my mistake(s)?
You are selecting your content divs wrong: