Dhruv Tyagi Dhruv Tyagi - 5 months ago 34
PHP Question

creating table into the Javascript

Actually i am creating a Modal and in the modal some dynamic data is to shown but my problem is while i insert the Modal body through the .html tag, I am unable to iterate my object Array into the .html tag,

Here is my Script:

echo "<script>
function myFunction(order){
$('.modal-body').html('<table>'
+'<tr>'

+'<th>'+'<b>S.No</b>'+'</th>'
+'<th>'+'<b>Name</b>'+'</th>'
+'<th>'+'<b>Quantity</b>'+'</th>'
+'<th>'+'<b>Personalization</b>'+'</th>'

+'</tr>'
+'<tr>'
var myOrder = order; //Here is my problem i want to iterate my Order object here and populate the rows through this
var arrayLength = myOrder.length;

+'<td>'+'Bill Gates'+'</td>'
+'<td>'+'555 77 854'+'</td>'
+'<td>'+'Bill Gates'+'</td>'
+'<td>'+'555 77 854'+'</td>'
+'</tr>'
+'</table>');
$('#myModal').modal({backdrop: false});
}
</script>";


Here is My Modal:

//<!-- Modal -->
echo"<div class='modal fade' id='myModal' role='dialog'>";
echo"<div class='modal-dialog'>";

// <!-- Modal content-->

echo"<div class='modal-content'>";
echo"<div class='modal-header'>";
echo"<button type='button' class='close' data-dismiss='modal'>&times;
</button>";
echo"<h4 class='modal-title'><center>Order Details</center></h4>";
echo"</div>";
echo"<div class='modal-body'>";

// echo "Order Number : " . "<script> ('.modal-body').html(order.order_id) </script>" ."<br>";

echo"</div>";
echo"<div class='modal-footer'>";
echo"<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>";
echo"<button type='button' class='btn btn-default' >Update</button>";
echo"</div>";
echo"</div>";

echo"</div>";
echo"</div>";

Answer

I guess you want something like

function myFunction(order) {
    var result = '<table>' // + '<tr>'... etc

    order.items.forEach(function(entry) {
        result += '<tr>'
                  + '<td>' + order.order_id + '</td>'  // Or whatever field is "S. no"
                  + '<td>' + entry.title + '</td>'
                  + '<td>' + entry.quantity + '</td>'
                  + '<td>' + (entry.personalization || '') + '</td>'
                + '</tr>';
    })

    result += '</table>';
    $('.modal-body').html(result);
}

In the line where you have var myOrder = order. On the other hand, the order object only has one order_id so it will be the same for everything.

Also this file doesn't need to change so you don't need to echo scape it but serve as javascript or inside <script> tag.