AJAX to reload DIV with PHP include()?

00PS

[H]ard|Gawd
Joined
May 5, 2009
Messages
1,798
Hey all,

I'm *trying* to use AJAX to update/reload a DIV on a page, but I'm running into a snag. Bare with me, JS is very new to me.

I have a a PHP page that creates a table of form cells. The cells are populated with data that comes from a SQL database. When I click on a cell and change the value, that cells new value is updated in the database. Where I'm struggling is, reloading that table on the page.

Here is a general snip-it of what I'm working with:
Code:
<div id="table">
  <div id="blah">
    <?php include("tableBuilder.php"); ?>  <---this is what builds the table
  </div>
</div>

<script type='text/javascript'>
// some JS code to parse info
  $('#theID).mouseleave(function() {
    //update SQL database using POST - works
    $('div#table').load("index.php #blah");  <--- this is my problem 
    //window.location.reload(true);  <---this is works...but then whats the point of using ajax?
   });
</script>

I'm using $('div#table').load("index.php #blah"); which works only once. Unfortunately, it will not continuously reload/execute the JS on the next mouseleave(). If I do a window.location.reload(true); then the whole page refreshes and everything is great...but then what is the point of ajax if everything reloads, right? (note: before I do the mouseleave() I'm doing a click() for the <input>).

I've tried $('div#blah').load("index.php #blah"); and all this does is double the div with the same ID. Any ideas? Hopefully this is clear enough...
 
Last edited:
I don't see a closing bracket for your mouseleave function. Don't know much java myslef...
 
Sorry about that...just a typo as I was writing this up.
 
The reason the mouseleave event doesn't fire after the first time is because when you replace #table, any events attached to child elements are no longer valid.

Instead of
Code:
$('#theID').mouseleave(function() {
    ...
});
try using the .on() function, such as
Code:
$('#parent').on('mouseleave', '#theID', function() {
    ...
});
where #parent (or any other selector, doesn't have to be ID specifically) is a parent element of #theID.

The .on() function attaches an event handler to #parent and only fires onmouseleave for #theID, even if it has been replaced by AJAX or other DOM manipulation, unlike .mouseleave().

For more information search Google for attaching event handler to dynamic content with jQuery.

Also note that you're missing a single quote in your selector.
 
Last edited:
Thanks Snowknight. I played around with the .on() function, but unfortunately, I still can't get it to work. I'm going to continue tinkering since I think you've put me on the right track.
 
Back
Top