How to get the id of a div by using attr("id"); ?

How to get the id of a div by using attr("id"); ?

index.php  
 if (idx == 8) {
        var str="<?php echo $username1; ?>";
        document.write(str);
            jQuery.get("usermessage.php?username="+str, function(data) {
                document.write(data);
                var msgIDss = $(".messagepiece:last").attr("id");
                document.write(msgIDss);
               });
    }

usermessage.php
<?php
$username1=$_GET["username"];
$query2 = "SELECT id, message, datetime FROM messages WHERE username='{$username1}' ORDER BY id";
            $result2 = mysql_query($query2,$connection) or die (mysql_error());
            confirm_query($result2);
            $num = mysql_num_rows($result2);
            while($userinfo = mysql_fetch_array($result2)){
                $msgID= $userinfo['id'];
                echo "<div class=\"messagepiece\" id=\"" . $msgID . "\">" . $userinfo['id'] . $userinfo['message'] . "<br><span style=\"font-size:13px; color:orange;\">" . $userinfo['datetime'] . "</span></div>|";       
            }
?>

My problem is document.write(msgIDss) display empty / blank value.

on index.php, I have tested document.write(data); and it works. I have tested document.write(str) and it work too. I also tested open usermessage.php manually and it success display all the div(s), so usermessage.php page is not the problem. I guess the problem is on this line of code var msgIDss = $(".messagepiece:last").attr("id") . How to fix it? Please help me.