简体   繁体   中英

Ajax only gives data after page reload

I am trying to create a notification button for an inactive article for my blog and I don't want admin to reload his/her page to see a new inactive article submitted, so I want to do this with AJAX.

I prepend html data to:
<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">

But my code only loads an new result after page reload.
Also, the each loop is repeating same data 2 times.

What's going wrong?

<script>
    $.ajax({
    type: "POST",
    url: 'inc/file.php',
    dataType: 'json',
    success: function(response)
    {
        if (response) {

            var html = '';
            $.each(response, function(key, value){
                html += "<li><a href='editArticle?id="+response.id+"&amp;act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";

            })
            $('#menu1').prepend(html);
            $('#number').text(response.number);

        }
    }
});
</script>

Here is my file.php while is fetching only one data:

<?php 

require $_SERVER['DOCUMENT_ROOT'].'/config/init.php';

require CLASS_PATH.'article.php';

$article = new Article();

$list = $article->getInactiveArticle();
$number = $article->countInactiveArticle();

$output = [];
foreach ($list as $lists) {
    $output['title'] = $lists->title;
    $output['id'] = $lists->id;
    $output['story'] = $lists->story;
    $output['number'] = $number[0]->inactive_articles;
}

echo json_encode($output);

Try to use setTimeout() function.

function timeout() {
  setTimeout(function(){ 
    $.ajax...

    timeout()
  }, 3000);

}

Have a look docs here

You can test the following code block.

It checks every 5 seconds and performs the operations.

    $(document).ready(function () {
    var eint = window.setInterval(function () {
            $.ajax({
            type: "POST",
            url: 'inc/file.php',
            dataType: 'json',
            success: function(response)
            {
                if (response) {

                    var html = '';
                    $.each(response, function(key, value){
                        html += "<li><a href='editArticle?id="+response.id+"&amp;act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";

                    })
                    $('#menu1').prepend(html);
                    $('#number').text(response.number);

                }
            }
        });
    },5000);
)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM