queenie
queenie

Reputation: 29

button not working when using javascript

My buttons are not bringing me to the next page. When I check for errors, it gives below error:

Uncaught TypeError: Cannot read property 'categoryID' of undefined" at line 53

I am unable to find any one with the same problem as me on this platform hence, the appeal for help.

There is no errors for my PHP.

$(document).ready(function () {
getcategories();

function getcategories() {
    var url = serverURL() + "/getcategories.php";

    var JSONObject = {
        "categoryID": localStorage.getItem("categoryID")
    };

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (arr) {
            _getCategoryResult(arr);
        },
        error: function () {
            validationMsg();
        }
    });
}

function _getCategoryResult(arr) {
    var t
    if ($.fn.dataTable.isDataTable('#categoryresult')) {
        t = $('#categoryresult').DataTable();
    }
    else {
        t = $('#categoryresult').DataTable({
            "searching": false,
            "lengthChange": false
        });
    }
     t.clear();

    //loop for the number of results found by getcategories.php
    for (var i = 0; i < arr.length; i++)
        //add a new row
        t.row.add([
            arr[i].categoryID,
            arr[i].categoryname,
            "<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
        ]).draw(false);

    $("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) { //error 
        var data = event.data;
        showcategory(data.id);
    });

}
$("#categoryresult").show();

function showcategory(categoryID) {
    //alert(categoryID);
    window.location = "showlist.html?categoryID=" + categoryID;

}

});

Upvotes: 0

Views: 62

Answers (1)

Septi Rito Tombe
Septi Rito Tombe

Reputation: 106

maybe you want to try this

for (var i = 0; i < arr.length; i++){
    //add a new row
    t.row.add([
        arr[i].categoryID,
        arr[i].categoryname,
        "<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
    ]).draw(false);

$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) { //error 
    var data = event.data;
    showcategory(data.id);
})};

You forgot to put enclosing in your for loop, thus, arr[i] = undefined

Upvotes: 1

Related Questions