Marc Marc - 1 month ago 15
Ajax Question

How to add new row to table after submission using AngularJS, AJAX, and XML

I am new to AngularJS and am trying to convert from JQuery to Angular. I know I am using JQuery snippet within .success but I highly doubt it'll work but this should give you an idea of what I am trying to do. I cannot seem quite figure out how to add new row to the table after the form submission. I was trying to keep adding new entry to the table but nothing works. If you know a good, simple snipped to get started, it will be greatly appreciated. Here's the code I have so far:

HTML:

<table id="tblLogEntry">
<tr id="tableheadings">
<th class="dateCol dateSize">Date</th>
<th class="trainingCol">Training</th>
<th class="successCol successSize">Success?</th>
</tr>
</table>


Angular:

var logApp = angular.module('logApp', []);

logApp.controller('logController', ['$scope', '$http', function($scope, $http) {

$scope.statuses = [
{value:'Yes'},
{value:'No'}
];

$scope.logData = {};

$scope.processLog = function(isValid) {

if (isValid) {
$scope.isProcessing = true;
$http({
method: 'POST',
url: 'LogEntryFile.php',
data: $.param($scope.logData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
var parser = new DOMParser();
var parsedXML = parser.parseFromString(data, "text/xml");
var today = parsedXML.getElementsByTagName("today")[0].childNodes[0].nodeValue;
var log = parsedXML.getElementsByTagName("log")[0].childNodes[0].nodeValue;
var status = parsedXML.getElementsByTagName("status")[0].childNodes[0].nodeValue;
$('#tableheadings').after('<tr>\n\
<td>' + {{ logData.today }} + '</td>\n\
<td>' + {{ logData.log }} + '</td>\n\
<td>' + {{ logData.status }} + '</td></tr>');
});
}

};

$scope.clearFields = function() {
$scope.logData = "";
};

}]);


LogEntryFile.php:

$log = new Log();

$log->dateoflog = $_POST["today"];
$log->training = $_POST["log"];
$log->success = $_POST["status"];

$isLogValid = $log->validateLog();

if ($isLogValid) {
insertLog($log->dateoflog, $log->training, $log->success);

echo ('<logentry>'
. '<today>' . $log->dateoflog . '</today>'
. '<log>' . $log->training . '</log>'
. '<status>' . $log->success . '</status>'
. '</logentry>');
} else {
header("Location: index.php");
}

Answer

Use the AngularJS ng-repeat directive:

<table id="tblLogEntry">
    <tr id="tableheadings">
        <th class="dateCol dateSize">Date</th>
        <th class="trainingCol">Training</th>
        <th class="successCol successSize">Success?</th>
    </tr>
    <tr ng-repeat="row in rowArray">
        <td>{{row.today}}</td>
        <td>{{row.log}}</td>
        <td>{{row.status}}</td>
    </tr>           
</table>

The ng-repeat directive will compile and add to the DOM a row for each row object in the array called rowArray.