Referring the json data to my html template - json

I am getting some data from the database in the form JSON through ajax. I can display the data with some HTML code inside the ajax code but this is not what I want. I want to refer this data with the help of some id to my actual table above... Is it possible or anyone has some idea?
Below is my code
//My code
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
#foreach($students as $student)
<tbody>
<tr>
<th>{{$student->id}}</th>
<td>{{$student->student_id}}</td>
<td>{{$student->first_name}} {{$student->last_name}}</td>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
#endforeach
</table>
//My javascrip
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
// $('#studentsData').html(response);
$('table[id="studentsData"]').empty();
$.each(data, function(key, value) {
var markup = '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
$('table[id="studentsData"]').append(markup);
});
}
});
}
});
});

Related

Add a table row from JSON input

I am trying to add a row to a HTML table from JSON input using AJAX. I only want specific columns added. I am able to get the table to show; however the rows are not added.
Please see below for the HTML and AJAX (with the returned JSON).
HTML:
<html>
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="js/table2excel.js"></script>
<link rel="stylesheet" href="style.css">
<script src="js/tableTest.js"></script>
</head>
<body>
<p><button id="btn-export">Export</button></p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr>
<td id='adActivityName'></td>
<td id='adStartDate'></td>
<td id='adEndDate'></td>
</tr>
</tbody>
</table>
</body>
</html>
AJAX (with JSON):
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity information.');
})
.done(function(responseJson1a) {
dataType: "json";
// alert(JSON.stringify(responseJson1a));
// [{"adId":"2","grpId":"2","adActivityID":"2","adActivityName":"Visit Ryde Fire Station","adStartDate":"2017-05-24","adEndDate":"2017-05-24"}]
for (i=0; i < responseJson1a.length; i++) {
$('#adActivityName').append("<td>"+a[i].adActivityName+"</td>");
$('#adStartDate').append("<td>"+a[i].adStartDate+"</td>");
$('#adEndDate').append("<td>"+a[i].adEndDate+"</td>");
}
});
}
You are Not appending table rows in a proper way
When you have multiple rows to append you need to create multiple row tags and append the data like this
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody id="mytablebody">
</tbody>
</table>
Javascript:
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity
information.');
})
.done(function(responseJson1a) {
var tablebody = "";
try{
for (i=0; i < responseJson1a.length; i++) {
tablebody += "<tr><td>"+responseJson1a[i].adActivityName+"</td><td>"++responseJson1a[i].adStartDate+"</td><td>"++responseJson1a[i].adEndDate+"</td></tr>";
}
$("#mytablebody").empty();
$("#mytablebody").append(tablebody);
}
catch(e){
console.log(e);
}
});
}

ReactJS select Initial value not reflected in view

I am trying to set an initial value for a select, but not showing in the view.
My jsx:
var SelectOKNO = React.createClass({
render() {
return (
<div>
<select className="selectpicker" value={this.props.value}
onChange={this.props.onChange.bind(this)}>
<option value=""></option>
<option value="OK">OK</option>
<option value="NO">NO</option>
</select>
</div>
)
}
});
var Detalle = React.createClass({
getInitialState: function() {
return({
ID:'',
UREFValue: '',
URCorrectoValue: '',
ConcordanciaValue: '',
PruebasValue: '',
EmergenciasValue: '',
ComentarioValue: '',
EstadoValue:'',
rec_fecha_aprobacion:'',
rec_aplica_control: '',
rec_auditor: ''
});
},
handleChange: function (key) {
return function (e) {
var state = {};
state[key] = e.target.value;
this.setState(state);
}.bind(this);
},
componentDidMount: function() {
$.ajax({
url: 'url',
data: { //Passing data
id: $("#hdnID").val()
},
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
ID:data.rec_id,
UREFValue:data.rec_inconveniente_usuario_ref,
URCorrectoValue:data.rec_usuario_ref_correcto,
ConcordanciaValue:data.rec_concordancia_doc,
PruebasValue:data.rec_pruebas,
EmergenciasValue:data.rec_emergencia,
ComentarioValue:data.rec_comentario,
EstadoValue: data.rec_estado,
rec_fecha_aprobacion:data.rec_fecha_aprobacion,
rec_aplica_control: data.rec_aplica_control,
rec_auditor: data.rec_auditor
});
}.bind(this),
error: function(xhr, status, err) {
}.bind(this)
});
},
render() {
return (
<form onSubmit={this.handleSubmit}>
<br/>
<table className="table borderless">
<tr className ="row">
<td>Usuario Referente:
<SelectOKNO value={this.state.UREFValue} onChange={this.handleChange('UREFValue').bind(this)}/>
</td>
<td>UR Correcto:
<textarea rows="3" className="form-control noresize" value={this.state.URCorrectoValue} onChange={this.handleChange('URCorrectoValue')} />
</td>
</tr>
<tr className ="row">
<td>Concordancia:
<SelectOKNO value={this.state.ConcordanciaValue} onChange={this.handleChange('ConcordanciaValue')}/>
</td>
<td>Pruebas:
<SelectOKNO value={this.state.PruebasValue} onChange={this.handleChange('PruebasValue')}/>
</td>
</tr>
<tr className ="row">
<td>Emergencias:
<SelectOKNO value={this.state.EmergenciasValue} onChange={this.handleChange('EmergenciasValue').bind(this)}/>
</td>
<td>Comentario:
<textarea rows="3" className="form-control noresize" value={this.state.ComentarioValue} onChange={this.handleChange('ComentarioValue')} />
</td>
</tr>
<tr className ="row">
<td>
<select className="selectpicker" value={this.state.EstadoValue}
onChange={this.handleChange('EstadoValue')}>
<option value="Abierto">Abierto</option>
<option value="EN_PROCESO">En Proceso</option>
<option value="CON_INCONVENIENTES">Con Inconvenientes</option>
<option value="COMPLETO">Completo</option>
</select>
</td>
<td>
<button type="submit" className="btn btn-default">Guardar</button>
</td>
</tr>
</table>
</form>
)
}
});
When page loads, all the select shows value like ''.
But in debug view of chrome I can see the value
How to set selected on options elements. Also, check what that means in React.
Finally, some nice libraries:
react-select and
react-bootstrap

select all checkboxes with angular JS

I am trying to select all checkboxes with one single checkbox. But how to do that?
This is my HTML:
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<!-- userlist -->
<!--<div id="scrollArea" ng-controller="ScrollController">-->
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
I create an extra checkbox to selecet and unselect all checkboxes.
JS:
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = true;
});
};
});
I tried this too, but none of them works for me :(
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = $scope.selectAll;
});
};
You are missed the container divs with ng-controller and ng-app and angular.module.
user.select = $scope.selectAll is the correct variant.
https://jsfiddle.net/0vb4gapj/1/
Try setting the checked boxes against each user to be checked when the top checkbox is checked:
<input type="checkbox" ng-model="selectAll"/>
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select" ng-checked="selectAll"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
Here is a JSFiddle you can use ng-checked with a variable on it like user.checked (or use the user.select as you want)
<div ng-app="app" ng-controller="dummy">
<table>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>
<input type="checkbox" ng-click="usersetting(user)" ng-checked="user.checked" ng-model="user.select">
</td>
<td><tt>{{user.select}}</tt>
<br/>
</td>
</tr>
</table>
<button ng-click="checkAll()">Check all</button>
</div>
JS:
var app = angular.module("app", []);
app.controller('dummy', function($scope) {
$scope.users = [{
id: 1,
name: "Hello",
select: 1
}, {
id: 2,
name: "World",
select: 1
}, ];
$scope.checkAll = function() {
angular.forEach($scope.users, function(user) {
user.checked = 1;
});
}
});
Simple use the following code
HTML
<input type="checkbox" ng-model="checkboxes.checked" data-ng-click="checkAll()" class="select-all" value="" />
JS
$scope.checkAll = function() {
angular.forEach($scope.users, function(item) {
$scope.checkboxes.items[item._id] = $scope.checkboxes.checked;
$scope.selection.push(item._id);
});
}

using ng-repeat to display data in json file

I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);

Add data from GET-request to table in HTML using ng-repeat

I'm having trouble with adding rows to a table in my HTML, which comes from an array containing objects.
When I run my code I do a $get request like so:
var app = angular.module('TM', []);
app.controller('tableController', function($http){
this.protocolList = [];
// Initialise array
$http.get('../protocols').success(function(data) {
console.log('Success ' + data);
this.protocolList = data;
angular.forEach(this.protocolList, function(value, key) {
console.log(key + ': ' + value.id + ' - ' + value.name);
});
})
.error(function(){
console.log('Error ' + data)
});
});
When I open up my web browser, I see the following:
My problems occure when I try to add this to a table in my HTML-file:
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="c in tctrl.currentDataObject.tableColumns"> {{ c }} </th>
</tr>
</thead>
<!-- This does not ouput anything...-->
<tbody>
<tr ng-repeat="(key, value) in tctrl.protocolList">
<td> {{ value }} </td>
</tr>
</tbody>
</table>
Any help will be much appreciated.
U don't need to inject $scope like this to get access to the DOM??
app.controller('tableController', function($scope,$http){
Im not sure if it is implicit.
Try this simple example:
app.controller('tableController', ['$scope', '$http', function($scope, $http){
$scope.protocolList = [];
// Initialise array
$http.get('../protocols').success(function(data) {
console.log('Success ' + data);
$scope.protocolList = data;
})
.error(function(){
console.log('Error ' + data)
});
}]);
HTML:
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="c in tctrl.currentDataObject.tableColumns"> {{ c }} </th>
</tr>
</thead>
<!-- This does not ouput anything...-->
<tbody>
<tr ng-repeat="item in protocolList">
<td> {{ item.id }} </td>
<td> {{ item.name }} </td>
</tr>
</tbody>