Skip to content
Advertisement

is there a way to update a div with new content only using ajax

This is the div that i am updating

but i want to add a active class to the (li) item every time the div refreshes the active class goes away so i don`t want to refresh all the data in the (ul) but only add (li) if there is a new data in the database, with out refreshing the previous (li) items

<div id="contacts">
    <ul id="rooms" class="rooms">
        <!-- This is where the data get inserted -->

        <!-- the ajax call and this  -->

        <li class='contact' data-val='<?php echo $room['id']; ?>'>
            <div class='wrap'>
                <div class='meta'>  
                    <p class='name'><?php echo $room['sender']; ?></p>
                    <p class='preview'><?php echo $room['senderemail']; ?></p>
                </div>
            </div>
        </li>


    </ul>
</div>

this is my ajax call

$(document).ready(function() {
    var interval = setInterval(function(){
        $.ajax({
            url: 'rooms.php',
            success: function(data){
                $('#rooms').html(data);
            }
        });
    }, 1000);
});

in the room php

    $rooms = get_rooms();
    foreach($rooms as $room){
        ?>
        <li class='contact' data-val='<?php echo $room['id']; ?>'>
            <div class='wrap'>
                <div class='meta'>  
                    <p class='name'><?php echo $room['sender']; ?></p>
                    <p class='preview'><?php echo $room['senderemail']; ?></p>
                </div>
            </div>
        </li>
        <?php
    }

the get_rooms() function

function get_rooms() {
        $sql = "SELECT id, sender, senderemail FROM chatroom ";
        $result = mysqli_query($GLOBALS['dbh'], $sql);
        $rooms = array();   
        while($room = mysqli_fetch_assoc($result)){
            $rooms[] = array('id'=>$room['id'], 'sender'=>$room['sender'], 
                              'senderemail'=>$room['senderemail']);
        }
        return $rooms;
}

Advertisement

Answer

You Just need to push new data to the div as below just replace your line with:

$('#rooms').append(data);

this will add new <li> in your existing <div> after the last <li>

jquery append()

To get the id of the last <li>

var lastId = $( "#rooms li" ).last().attr('id');

Once you get the last id then pass it in your ajax call.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement