Jerielle Jerielle - 5 months ago 8
Javascript Question

Ajax wont trigger in implementing a polling in Jquery and PHP

I am trying to add a functionality that gets the real time total price using a polling technique and I already did some functions in the PHP side to retrieve tha latest values. My problem is I can't perform the ajax after the timeout. I don't know where's my error. Can you help me?

function getTotalContract() {
$.ajax({
url: "<?php echo site_url('contracts/contracts/get_contract_total'); ?>",
success: function(data) {
console.log(data);
},
dataType: 'json',
complete: getTotalContract,
timeout: 1000 //every second
})
}


here's the PHP side. I am using Codeigntier 3

public function get_contract_total() {
$json = array();
$json['total'] = $this->Contracts_model->get_total_contract();
json_header();
echo json_encode($json);
}


Can you help me?

Answer

timeout is not a repeating timer...it is a setting to go into error callback if duration of request exceeds the timeout amount

if you want to repeat the ajax you need to use window timers like setTimeout() or setInterval()

You could do something like:

function getTotalContract() {
    $.ajax({
        url: "<?php echo site_url('contracts/contracts/get_contract_total'); ?>",
        success: function(data) {
            console.log(data);
             setTimeout(getTotalContract, 2000);
        },
        dataType: 'json'

    })
}