I have a query Select name, age from users and I want it to return the content to jquery with a specific format:
var externalDataRetrievedFromServer = [
{ name: 'Bartek', age: 34 },
{ name: 'John', age: 27 },
{ name: 'Elizabeth', age: 30 },
];
On a php side so far I have:
$fetch = "SELECT name, age from users";
$result = $mysqli->query($fetch);
$data = array();
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
and on jquery site I have:
$.ajax({
url: './getJson.php',
type: "POST",
data: {
users: users
},
dataType:'text',
success: function(ans)
{
alert(ans);
but it returns me data in a format:
[{"name":"Bartek","age":"34"},{"name":"John","age":"27"},{"name":"Elizabeth","age":"30"}]
I need the specific format that I mentioned at the beginning of my post, because now my current logic (that I don't want to change) throws me an error: data.forEach is not a function in this line:
function buildTableBody(data, columns) {
var body = [];
body.push(columns);
data.forEach(function(row) {
var dataRow = [];
columns.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
where data is the data in a format that I have right now. So how can I change the format?
A little bit more details here:
I'm using buildTableBody() here:
function table(data, columns) {
return {
table: {
headerRows: 1,
body: buildTableBody(data, columns)
}
};
}
However, when I changed the datatype from text to json, I'm getting the error:
Uncaught TypeError: Cannot read property 'toString' of undefined
from the method buildTableBody.
When I do alert(ans) now, I'm getting:
[object Object],[object Object],[object Object]
Do you have any clues how could I fix it?
---- another edit:
This is exactly what I want to achieve:
var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', age: 30 }, ];
function buildTableBody(data, columns) { var body = [];
body.push(columns);
data.forEach(function(row) {
var dataRow = [];
columns.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
function table(data, columns) { return { table: { headerRows: 1, body: buildTableBody(data, columns) } }; }
var dd = { content: [ { text: 'Dynamic parts', style: 'header' }, table(externalDataRetrievedFromServer, ['name', 'age']) ] }