Fetch data using ajax

Started by helenedwards, 10-08-2016, 03:04:16

Previous topic - Next topic

helenedwardsTopic starter

hi, I have two tables in my database first one id and the other one text.

this is index.php file I can fetch the data from db like this way


<?php include "config.php"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>

<ul>

<?php
$result = $db->query("select * from veri ORDER BY id DESC ");
while ($row = $result->fetch_object()) {
echo '<li id="'.$row->id.'">'.$row->text.'</li>';
}


?>
</ul>

</body>
</html>
what I want to do is that once I insert a new item into a database this item is supposed to show up on top of the list without refrehing the page .This is my code but It doesnt work What am i doing wrong

ajax.js file

$(function () {

    $ajaxLoad = function () {

        var lastid = $("ul li:first").attr("id");

        $.ajax({
            type: "post",
            url: "ajax.php",
            data: {"lastid": lastid},
            dataType: "json",
            success: function (result) {
                if (result.error) {
                    $("#result").html(result);

                }
                else{
                    $("ul").prepend(result.data);
                }
            }

        });
    }
    setInterval("ajaxLoad()",1000);

});


this ajax.php file

<?php

require "config.php";

if (
$_POST) {

    
$lastid $_POST["lastid"];
    if (!
$lastid) {
        
$array["error"] = "something  is wrong";
    } else {
        
$query $db->query("select * from veri where id>$lastid ORDER  by id DESC ");
        if (
mysqli_affected_rows()) {
            while (
$row $query->fetch_object()) {
    
$array["data"]='<li id="'.$row->id.'">'.$row->text.'</li>';
            }
        } else {
            
$array["error"] = " there is no new record";
        }
    }
    echo 
json_encode($array);
}
?>
newbielink:http://watch68.net/movie-genres/romance [nonactive]
  •