2

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?

9
  • 1
    var result = data; $.each($.parseJSON(result), function(k, v) { alert(k + ' is ' + v); }); Commented Jul 21, 2015 at 6:29
  • then this question is about JS and not PHP?! Commented Jul 21, 2015 at 6:31
  • Yes it is Js but I still use php to pass the array Commented Jul 21, 2015 at 6:31
  • Unless I'm missing something, the Output of Data that you show is not valid JSON. HondaHonda maker should not be there. Commented Jul 21, 2015 at 7:07
  • 1
    @Vani - well, what do you want the table to look like? You have essentially two arrays returned. Do you wish to have a simple 2 column table, with each array in one of the columns? Commented Jul 21, 2015 at 7:20

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

5 Comments

do I need to include any library for this code to work? I've copy pasted this in my success function and it doesn't show anything even with hardcoded value.
@Vani - nope. There are no dependencies for this code. I've updated my answer to include a fully-functioning example. What did your debugger tell you was the problem?
no error shown actually..But I included this code in success function of ajax but you used before head tag...Could this be the reason? I tried to include it in head section and call the function in success function but still i can't see the table
Interesting.. Well, you should just pass the results of the ajax call to the parseAndCreateTable function and then append the result to the desired container. Actually, my code is inside the head. Something else you could consider is using a jQuery method to set the innerHTML of en element - just get the table from the function call and then get it's html, then use the jQuery method of appending this. I.e `var resultTable = parseAndCreateTable(data); var tblHTML = resultTable.outerHTML; ** set contents of element using jQuery method ** (I dont jQuery, so I dunno what else to suggest)
I included your function in head and passed data into parseAndCreateTable function then appended into the container just like you mentioned and it returned the table! Thank you!
1

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');

6 Comments

It says, No Type data available No makers data available
try data[0].type and data[0].maker
just do a JSON.stringify(data) and paste the text here. I need to see the response
[{"type":["4 wheeler","flying ycar"],"maker":["Honda","AUdi"],"rate":[["1","89"],["1","70"],["1","57"],["2","78"],["2","56"],["2","34"]]}]
I tried and it outputs 0, 1, 2, 3, 4, 5, 6, 7. twice. But what is it? How do I access each element in each array?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.