SoldierCorp SoldierCorp - 1 year ago 47
jQuery Question

How create table or append from JSON format?

After process a tiny search engine with ajax-jQuery, and functions in PHP, I've a Array JSON and I want process this for append rows in table exists but I get confused.

The JSON format from query mysql is OK, but I don't know how process data to generate table or append in my exists table.

I think that is applied each for taking each element of JSON but I can not think as.

Note: My JSON Code was generate to this this way

...........
$jsonSearchResults = array();
while ($row = mysql_fetch_assoc($result)) {
$jsonSearchResults[] = array(
'clavemat' => $row['cve_mat'],
'tipomat' => $row['tipo_mat'],
'titulomat' => $row['titulo_mat'],
'autormat' => $row['autor_mat'],
'editmat' => $row['edit_mat'],
'success' => 'success'
);
}
echo json_encode ($jsonSearchResults);


Table HTML

.........
<table class="busqueda">
<tr>
<th scope="col">Clave</th>
<th scope="col">Tipo</th>
<th scope="col">Título</th>
<th scope="col">Autor</th>
<th scope="col">Editorial</th>
</tr>
</table>
........


JSON CODE

[
{
"clavemat":"LICOELMCUS",
"tipomat":"Libro",
"titulomat":"Contabilidad",
"autormat":"Elias Flores",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"LICUDEMCNU",
"tipomat":"Libro",
"titulomat":"Curso java",
"autormat":"Deitel",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"REECMUMUNU",
"tipomat":"Revista",
"titulomat":"Eclipses",
"autormat":"Muy Interesante",
"editmat":"Muy interesante",
"success":"success"
},
{
"clavemat":"TEPLPLTENU",
"tipomat":"Tesis",
"titulomat":"Platanito Show",
"autormat":"Platanito",
"editmat":"Telehit",
"success":"success"
}
]


AJAX.JQUERY FILE

$.ajax({
type: "POST",
url: action,
data: dataSearch,
success: function (response) {

if (response[0].success == "success") {
alert("Si hay datos");
} else {
alert("No hay datos");
}

}
});
return false;
});

Answer Source

This should work

$.each(response, function (index, record) {
    var row = $("<tr />");
    $("<td />").text(record.clavemat).appendTo(row);
    $("<td />").text(record.tipomat).appendTo(row);
    $("<td />").text(record.titulomat).appendTo(row);
    $("<td />").text(record.autormat).appendTo(row);
    $("<td />").text(record.editmat).appendTo(row);

    row.appendTo("table.busqueda");
});

The above code appends rows to an existing table with class "busqueda".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download