0

I've got an AJAX request in my index.php to another file (get_code.php) that queries a DB and returns a json_encoded array to index.php, where it is converted to a string with JSON_stringify.

This works fine, but for the fact that it comes out on the page like so:

[{"code":"GG500","desc":"Desc 1","price1":"9.35","price2":"8.25","price3":"7.75","avg":"7.994198","lwcm":"7.9568","cost":"4.63"},
{"code":"GGC4","desc":"Desc 2","price1":"","price2":"","price3":"","avg":"504.666666","lwcm":"387.5","cost":"260.61"}]

Question:

How can I get this string and convert it into a normal array or whatever that I can display in an HTML table in index.php?

Current code:

index.php jQuery

if (!data.result) {
   $('#modal2').modal('show');
   $('.msgs').text(data.error);
   $('#cdnf').text(data.code);
   $('#tarray').text(JSON.stringify(data.tarray));
}

index.php HTML

<p id="tarray"></p><!-- needs to be a table -->

get_code.php PHP

$taq = mysql_query("SELECT * FROM variants")or die(mysql_error());
if($taq){
    $tarray = array();
    while($row = mysql_fetch_assoc($taq)){
            $tarray[] = array(
     'code' => $row['va_code'],
     'desc' => $row['va_description'],
     'price1' => $row['price_1'],
     'price2' => $row['price_2'],
     'price3' => $row['price_3'],
     'avg' => $row['average_price'],
     'lwcm' => $row['lwcm'],            
     'cost' => $row['cost']  
);
    }
};
die(json_encode(['tarray' => $tarray]));
13
  • you need to iterate the json object. Read the object and then print the values Commented Apr 8, 2017 at 12:11
  • JSON.parse is for decoding json into an array, JSON.stringify is for encoding array into json Commented Apr 8, 2017 at 12:11
  • OK thanks @Tushar - how do I go about this in the jQuery? Commented Apr 8, 2017 at 12:12
  • @hassan JSON.parse returns an error Unexpected token o in JSON at position 1 ? Commented Apr 8, 2017 at 12:13
  • depends on how you want to show the data. ;) you can create a table and populate each row or you can directly dump the data. It all depends on the requirement Commented Apr 8, 2017 at 12:14

2 Answers 2

1

Instead of:

$('#tarray').text(JSON.stringify(data.tarray));

loop over the data and create a table:

$('#tarray').html('').append(
    $('<table>').append(
        $('<tr>').append(
            $.map(data.tarray[0] || [], function (_, key) {
                return $('<th>').text(key);
            })
        ),
        data.tarray.map(function (row) {
            return $('<tr>').append(
                $.map(row, function (cell) {
                    return $('<td>').text(cell);
                })
            );
        })
    )
);

// Sample data
var data = {
    tarray: [{"code":"GG500","desc":"Desc 1","price1":"9.35","price2":"8.25","price3":"7.75","avg":"7.994198","lwcm":"7.9568","cost":"4.63"},
{"code":"GGC4","desc":"Desc 2","price1":"","price2":"","price3":"","avg":"504.666666","lwcm":"387.5","cost":"260.61"}]
};

$('#tarray').html('').append(
    $('<table>').append(
        $('<tr>').append(
            $.map(data.tarray[0] || [], function (_, key) {
                return $('<th>').text(key);
            })
        ),
        data.tarray.map(function (row) {
            return $('<tr>').append(
                $.map(row, function (cell) {
                    return $('<td>').text(cell);
                })
            );
        })
    )
);
th, td { border: 1px solid }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tarray"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Brilliant exactly what I was looking for! Thanks
how would I set it to nothing, so that if it's queried again the table's empty?
Add .html('') before the first .append. I updated my answer with it.
1

This is as per OP's need. I am just showing here an example of your correct JSON and how to iterate to get that in form of a table

Correct JSON object would look like below :

[{"code":"ABC123","desc":"Example description","price1":"3.00"},
  {"code":"BDC234","desc":"Example description2","price1":"3.50"}]

JSON into a table:

var obj=[{"code":"ABC123","desc":"Example description","price1":"3.00"},{
  "code":"BDC234","desc":"Example description2","price1":"3.50"}]
    var tbl=$("<table/>").attr("id","mytable");
    $("#div1").append(tbl);
    for(var i=0;i<obj.length;i++)
    {
        var tr="<tr>";
        var td1="<td>"+obj[i]["code"]+"</td>";
        var td2="<td>"+obj[i]["desc"]+"</td>";
        var td3="<td>"+obj[i]["price1"]+"</td></tr>";

       $("#mytable").append(tr+td1+td2+td3); 

    }
#mytable{
 padding:0px;
}
tr,td{
border: 1px solid black;
padding:5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div1'></div>

2 Comments

awesome, so do i set var obj=JSON.stringify(data.tarray); ?
Thanks for your help @Tushar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.