Ad

How To Pass This Array From Laravel Controller Via AJAX And Create A Table

- 1 answer

I have this array:

Array
(
    [0] => Array
        (
            [start_break] => 2019-05-23 09:01:23
            [end_break] => 2019-05-23 09:04:36
            [time_diff] => 0.05
        )

    [1] => Array
        (
            [start_break] => 2019-05-23 12:05:33
            [end_break] => 2019-05-23 12:07:19
            [time_diff] => 0.03
        )

)

I would like to pass it via AJAX and create a table in a modal. So far, I have this JS code:

    $.ajax({
        type: 'GET',
        url: 'get-breaks',
        data: {
            t_date: $t_date,
            emp_id: $emp_id
        }
        success: function (data) {
            //append to table
        },
        error: function (data) {
        }
   });

And this HTML table:

<table id="breaks-table">
   <tr>
     <th>Start Break</th>
     <th>End Break</th>
     <th>Time Difference</th>
   </tr>
</table>

I would like to append the array contents to the table body. I hope someone can help.

Ad

Answer

i assume successfully get array from controller

after get try like that

$.ajax({
        type: 'GET',
        url: 'get-breaks',
        data: {
            t_date: $t_date,
            emp_id: $emp_id
        }
        success: function (data) {
            //append to table
            if(data.dateArray) {
              data.dateArray.forEach(function(item,index) {
                      $("table#breaks-table").append(createTr(item));
              });
            }
        },
        error: function (data) {
        }
   });



function createTr(item) {
    var tr = '<tr>' +
           '<td class="className">' + item.start_break + '</td>' +
           '<td>' + item.end_break + '</td>' +
           '<td>' + item.time_diff + '</td>' +
        '</tr>';

    return tr;
 } 
Ad
source: stackoverflow.com
Ad