112233
112233

Reputation: 2466

How to display multidimensional array of json string in a table

I passed data fetched from database via ajax to be displayed in the html page. I managed to pass it in a multidimensional array from php script. Now I get the json string but I'm unsure on how to properly display the output in a html table.

Script

$("#submit").on("click",function()
    {

          $("#set_setting").submit(function(){            

            data = $(this).serialize()
            $.ajax({
              type: "POST",
              dataType: "html",
              url: "submit_setting.php", //Relative or absolute path to response.php file
              data: data,
              success: function(data) {
                  alert(data);
              //hide the form
              $("#set_setting").slideUp("slow");
              //show the result
             /* for (i = 0; i < data.length; i++) {
                  console.log(data);
                  $(".the-return").html(data);
              }*/

              console.log(data);
                $(".the-return").html(data);

              }

            });
            return false;

          });

        });

php script

$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo json_encode($json);

Output of data

HondaHonda maker[{"type":["flying car","3 wheleer","weird car","miracle car","tata car","see car","star car","mn car","jkcar","car test","ting","Honda"],"maker":["test maker","diamond car","ruby car","dont know car","titi car","saw car","moon car","ty car","ty car","car maker test","ting maker","Honda maker"]}]

How do I display this json string in html table?

Upvotes: 2

Views: 2054

Answers (2)

Amit
Amit

Reputation: 457

Something Like this maybe:

var typeMsg = ''
var makers = ''
if(data && data[0].type) {                //considering data is your response object
    for(var c in data[0].type) {
        typeMsg += c + ', ';
    }
}
if(data && data[0].maker) {   
    for(var c in data[0].maker) {
        makers += c + ', ';
    }
}

$('#elementForType').text(typeMsg && typeMsg.trim().replace(/,$/, "") + "." || 'No Type data available');
$('#elementForMakers').text(makers && makers.trim().replace(/,$/, "") + "."  || 'No makers data available');

Upvotes: 1

enhzflep
enhzflep

Reputation: 13089

Here's some vanilla JS that will do the trick. It's probably worth mentioning that you're returning an array of results, which only has a single element in it. This is the cause for the parsedResult[0] in my code. If you wanted to return the data for multiple html tables, you'd have parsedResult[1], parsedResult[2] etc, etc. This code doesn't account for such a situation - I've hard-coded it to work with just the first.

Result: (excuse the text formatting of an html table, if you would)

type    maker
flying car  test maker
3 wheleer   diamond car
weird car   ruby car
miracle car dont know car
tata car    titi car
see car saw car
star car    moon car
mn car  ty car
jkcar   ty car
car test    car maker test
ting    ting maker
Honda   Honda maker

Code:

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function newEl(tag){return document.createElement(tag);}

window.addEventListener('load', onDocLoaded, false);

var dummyResultString = '[{"type":["flying car","3 wheleer","weird car","miracle car","tata car","see car","star car","mn car","jkcar","car test","ting","Honda"],"maker":["test maker","diamond car","ruby car","dont know car","titi car","saw car","moon car","ty car","ty car","car maker test","ting maker","Honda maker"]}]';

function onDocLoaded()
{
    var ajaxResult = dummyResultString;
    var tblOfResults = parseAndCreateTable( ajaxResult );
    document.body.appendChild(tblOfResults);
}

function parseAndCreateTable(inputString)
{
    var rawResult = inputString;
    var parsedResult = JSON.parse(rawResult);
    var tableHeadings = [];

    // extract the name of the properties that the object has.
    for (var property in parsedResult[0]) 
    {
        if (parsedResult[0].hasOwnProperty(property))
            tableHeadings.push(property);
    }

    // make the table
    var tbl = newEl('table');
    var tbody = newEl('tbody');
    tbl.appendChild(tbody);

    // make the first row, with headings in it
    var tr = newEl('tr');
    var i, n = tableHeadings.length;
    for (i=0; i<n; i++)
    {
        var th = newEl('th');
        th.innerText = tableHeadings[i];
        tr.appendChild(th);
    }
    tbody.appendChild(tr);

    // now for the 'fun' part - the body itself.
    var curRowIndex, curColIndex, nRows = parsedResult[0][tableHeadings[0]].length, nCols = tableHeadings.length;
    for (curRowIndex=0; curRowIndex<nRows; curRowIndex++)
    {
        var tr = newEl('tr');
        for (curColIndex=0; curColIndex<nCols; curColIndex++)
        {
            var td = newEl('td');
            td.innerText = parsedResult[0][ tableHeadings[curColIndex] ][curRowIndex];
            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }

    return tbl; 
}
</script>
<style>
</style>
</head>
<body>
</body>
</html>

Upvotes: 1

Related Questions