Uncaught Typeerror: JS function

Asked

Viewed 51 times

1

Can help me understand where the mistake 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: Cannot set Property 'innerHTML' of null

Informs that it is on 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>
  • For him the html field that you are trying to populate does not exist. qd js is running.. this element does not exist in DOM. Look for information on the append. You can read this site: https://teamtreehouse.com/community/uncaught-typeerror-cannot-set-property-innerhtml-of-null-at-scriptjs29-at-scriptjs32

  • @Israelzebulon All fields exist in HTML.

  • 1

    It would be helpful if edit and put the HTML !

  • @wmsouza It repeats the lines with a sequence, leaving: bid_user_name_0, bid_user_name_1, bid_user_name_2

  • @dvd I didn’t understand the way you spoke.

1 answer

1


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

To avoid error apply the innerHTML only to the 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 a if to check whether the 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.