Uncaught TypeError: JS Function

1

Can you help me understand where the error is?

function atualizaLista(id_leilao) {
    if (id_leilao) {
        $.ajax({
            url: 'get.php',
            dataType: 'json',
            type: 'POST',
            data: 'id_leilao=' + id_leilao,
            global: false,
            success: function (data) {
                for (i = 0; i < data.histories.length; i++) {
                    biddingusername = data.histories[i].history.username;
                    biddingprice = data.histories[i].history.bprice;
                    biddingtime = data.histories[i].history.time;

                    document.getElementById('bid_user_name_' + i).innerHTML = biddingusername;
                    document.getElementById('bid_price_' + i).innerHTML = 'R$' + biddingprice;
                    document.getElementById('bid_time_' + i).innerHTML = biddingtime;
                }
            }, error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });          // fim ajax
    } // fim if
}

Uncaught TypeError: Can not set property 'innerHTML' of null

Tell me what's in this line:

document.getElementById('bid_user_name_' + i).innerHTML = biddingusername;

HTML:

<tr class="producthisrow">
    <td align="center" id="bid_user_name_<?= $q; ?>"></td>
    <td align="center" id="bid_price_<?= $q; ?>"></td>
    <td align="center" id="bid_time_<?= $q; ?>"></td>
</tr>
    
asked by anonymous 02.03.2018 / 03:29

1 answer

1

The problem is that the code is not finding the element by id within the for loop.

To avoid the error of applying innerHTML to only elements that exist on the page, place the lines:

document.getElementById('bid_user_name_' + i).innerHTML = biddingusername;
document.getElementById('bid_price_' + i).innerHTML = 'R$' + biddingprice;
document.getElementById('bid_time_' + i).innerHTML = biddingtime;

Within if to check that document.getElementById('bid_user_name_' + i) exists:

if(document.getElementById('bid_user_name_' + i)){
   document.getElementById('bid_user_name_' + i).innerHTML = biddingusername;
   document.getElementById('bid_price_' + i).innerHTML = 'R$' + biddingprice;
   document.getElementById('bid_time_' + i).innerHTML = biddingtime;
}
    
02.03.2018 / 04:20