Reputation: 761
I would like to display data using jquery and ajax in a table in my twig file.
The ajax request sent a post request to the controller, the controller tried to insert severl row from a csv file in the database, but some error data cannot be inserted and I would like to display these data to the client using ajax and jQuery.
The data should be displayed in a table in my twig file. Until now, I can return the data, but I can't display the data in a table.
This is my ajax code:
jQuery('#formulaire').ajaxForm({
beforeSubmit: function (arr, $form, options) {
var ids = [];
var values=[];
$('li.ui-selected').each(function(){
ids.push(this.id);
values.push(this.value);
});
arr.push({name:'hide', value:(ids)})
arr.push({name:'valueschamps', value:(values)});
},
success: function (result, request) {
var parsedData =JSON.parse(result);
jQuery('#data').append(parsedData.data);
//jQuery('#data').html(parsedData.data);
},
error: function () {
jQuery('#main-content').html("errors");
}
});
In my controller I have:
$response = new JsonResponse();
$dataToReturn = array('data' => $dataerror);
$response->setData($dataToReturn);
return $response;
The result returned is as follows:
I want to display the data returned by the controller in a table inside the twig file. I tested several solutions, but does not work.
Any Help please
Upvotes: 0
Views: 2173
Reputation: 637
The main problem is the backend returns plain JSON.
so jQuery('#data').append(parsedData.data);
will never work, since it is a javascript object.
You either have to create the elements via javascript as was previously suggested, or you have to return html with symfony. You can create a separate view for it if you like.
And then append the returned html like so:
jQuery('#data').append(result);
Upvotes: 1
Reputation: 1088
Did you try to loop over the json elements and create the table, for example:
function createTable(data) {
var rowData;
var rowHTML;
var tableHTML = "<table>";
for (var i = data.length - 1; i >= 0; i--) {
rowData = data[i];
rowHTML = "<tr>";
for (var k = rowData.length - 1; k >= 0; k--) {
rowHTML += "<td>" + rowData[k] + "</td>";
}
rowHTML += "</tr>";
tableHTML += rowHTML;
}
tableHTML += "</table>";
return tableHTML;
}
And call it in the success callback like this:
jQuery('#data').html(createTable(parsedData.data));
Upvotes: 2