Arthur Timmermans Arthur Timmermans - 1 month ago 9
Ajax Question

ajax call does not update

I made an Ajax call.
It shows the data on my site, but it does not update it automatically(without pressing f5(refreshing my site)) if I change it in the database.

This is my code:

$(document).ready(function(){
getname();
})
function getname(){
$.ajax({
type: 'post',
url: '../php/clas/name.php',
data: 'type=getthename',
dataType: 'json',
success: function(responseOrderData){
var showOrderData = '';
var rows = 0;
$.each(responseOrderData, function(index){
rows++;
showOrderData += '<tr>';
showOrderData += '<td>';
showOrderData += responseOrderData[index].name;
showOrderData += '</td>';
showOrderData += '</tr>';
console.log(responseOrderData);
});
if(rows == 0){
showOrderData += '<tr><td colspan="7"><center><i class="fa fa-refresh fa-spin"></i></center></td></tr>';
}
$('.orderData').html(showOrderData);
},
timeout: 1000,
error: function(error){
console.log(error);
}
})
}

Answer

You need to somthing like socket.io to make real time updates and send data from server to client but you can do the task using JavaScript setTimeout or setInterval to refresh html content without reloading the page

$(document).ready(function(){
    getname();
})
function getname(){
        $.ajax({
            type: 'post',
            url: '../php/clas/name.php',
            data: 'type=getthename',
            dataType: 'json',
            success: function(responseOrderData){
                var showOrderData = '';
                var rows = 0;
                    if(rows == 0){
                    showOrderData += '<tr><td colspan="7"><center><i class="fa fa-refresh fa-spin"></i></center></td></tr>';    
                }
                $.each(responseOrderData, function(index){
                    rows++;
                    showOrderData += '<tr>';
                    showOrderData += '<td>';
                    showOrderData += responseOrderData[index].name;
                    showOrderData += '</td>';
                    showOrderData += '</tr>';
                    console.log(responseOrderData);
                });

                $('.orderData').html(showOrderData);
                //wait 10 seconds after ajax called successfully
                setTimeout(getname,10000);
            },
            timeout: 1000,
            error: function(error){
                console.log(error);
            }
        })
    }