Andrea485 Andrea485 - 1 year ago 60
Ajax Question

Refresh element in a div ajax

I have a small web application that manages some lessons and reports the statistics for them (completed and not completed). When one clicks on the

button, I would like to refresh the statistics
of the lessons.

Here is the

$data = new MysqlClass();
$sql = "select * from Lessons";
$result = mysql_query($sql);
<div class="history">
while($row = mysql_fetch_array($result)) {
<h2>name: <?php echo $row['name']; ?>
<h2>completed: <?php echo $row['completed']; ?>

And the event handler attached to the

$(document).ready(function () {
type: "POST",
url: "statistic.php",
success: function(html){


I did not include the
function (which also makes an AJAX call) because it is not important.

I would like to refresh the statistics of lessons without refreshing the page. I tried to refresh it with an AJAX call but it did not update the data. Thank you in advance for your answers.

Answer Source

You have atleast 2 problems.

First, you need to do something with the variable html in your success callback.

Second, since completeLesson makes its own ajax call, you have to wait for that call to return before you put in your call to statistic.php. if you don't wait, there's a chance that the second Ajax call will be completed before the first and it won't bring in the new data.

One solution would be to pass completeLesson the second Ajax call as a callback function.

function completeLesson ( /* your other arguments */, callback) {
    // this would be the Ajax call already in completeLesson
    $.ajax ( {
        // whatever arguments you use for the ajax call
        success: function (data) {
            // the code you had in here before...
            // after all that code add these 2 lines
            if (callback)

And now, you change the event listener for finish to (assuming statistic.php is echo'd out between <div id="result"><?php include 'statistic.php'; ?></div> and also that you've added id="#hs" to the .history div):

$('.finish').click(function(event) {
    completeLesson(function() {
            type: "POST",
            url: "statistic.php",
            success: function(html) {

You may want to use $('#result').append(html) instead of prepend.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download