Search code examples
javascriptjsonalertstringify

i just want to print the data in alert but ever time it alert me [object Object] but i want that it will show my table data row


$.post("Hirarchi/addHirarchi",
    {/*'id':hirarchiId,*/'hirarchiName':hirarchiName,'level':HirarchiLevel},
        function(data) {


            $('#lblMessage').html (data);
            $('#txtHirarchiName').val('');
            $('#txtHirarchiLevel').val('');

                        var data = $.parseJSON(data);

                        $.each(data, function(a,b,c) {


                            alert(data);

                        });

        });

Solution

  • you can not pass object to alert. If you give object to it, it will [Object Object]. alert parameter must be string

    //for Each loop code
    $.each(data, function(index,value,list) { 
      alert(JSON.stringify(value)); //if you want to alert each object then use
      //data will not be accessible inside $.each you can access the same using 3rd parameter which list
      alert(JSON.stringify(list));
    });
    

    But the thing is why you gave alert in $.each and alerting same data. I'm assuming it is part of some functionality in your code. But that is not good practice to do.

    Update 1.

    Here is your answer with rendering table.

    Code

    drawTable(data);  /// call this line from your ajax success
    
    function drawTable(data) {
        var tData = data.tblHirarchi
        for (var i = 0; i < tData.length; i++) {
            if (tData[i] != null) {
                drawRow(tData[i])
            }
        }
    }
    
    function drawRow(rowData) {
        var row = $("<tr />")
        $("#personDataTable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
        row.append($("<td>" + rowData[0] + "</td>"));
        row.append($("<td>" + rowData[1] + "</td>"));
        row.append($("<td>" + rowData[1] + "</td>"));
    }
    

    Fiddle HERE