Update Individual MySQL Records on Checkbox Click with AngularJS - javascript

I am creating a golf tournament check-in app and want to be able to update an individual record in the MySQL database when a checkbox is clicked. So, when someone checks in they click the checkbox by their name and I want it to then update the database record of that person (the checked in column set to 1 for the specific id of the person) so that others can see that the person is checked in almost immediately.
I am not sure how to get both the id and the checkedin value to update only the affected record when a checkbox is clicked.
app.js
var checkinApp = angular.module('checkinApp', []);
checkinApp.controller('checkinController', function($scope, $http, $location, $anchorScroll) {
$http.get('lib/api.php').success(function(data) {
$scope.checkindata = data;
});
$scope.processForm = function(checkedindata) {
$http.post('lib/process.php', { gid : checkedindata.gid, checkedin : checkedindata.checkedin })
.then(function(data) {
console.log(data);
})
};
});
HTML/Output
<table class="table table-striped table-responsive">
<tbody>
<tr>
<th>Checked In</th>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
<th>Starting Hole</th>
</tr>
<tr ng-repeat="item in checkindata">
<td><input type="checkbox" name="checkedin" ng-model='checkedin' ng-change='processForm(checkedindata)' ng-checked="item.checkedin == 1"/></td>
<td>{{item.fname}}</td>
<td>{{item.lname}}</td>
<td>{{item.cname}}</td>
<td>{{item.hole}}</td>
</tr>
</tbody>
</table>
process.php
<?php
require_once('../includes/cred.php');
$checkedin = $_POST['checkedin'];
$sth = $dbh->prepare("UPDATE golfers SET checkedin=$checkedin");
$sth->execute();
DB Table
DB Table
Output
Output

Simply replace ng-change='processForm(checkedindata)'
by ng-change='processForm(item)'
and in your PHP code do something like :
$sth = $dbh->prepare("UPDATE golfers SET checkedin=$checkedin->checkedin WHERE gid=$checkedin->gid");

Related

How do i refresh or redraw table rows

Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});

How to generate automatically the sum price of a dynamic table using jquery?

I'm making a web-based POS. I have two table, one is for displaying the search products using jquery and when I clicked the product it will transfer to the second table. So my second table is dynamically dependent of what the user clicked. This is my table look like with css.
I want to get the total price of Sub.Total column automatically and display to the bottom specially in the Total p tag.
This is my html table code.
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
This is my query from search box.
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<tr class='js-add' data-barcode=".$row['id']." data-product=".$row['product_name']." data-price=".$row['sell_price']." data-unt=".$row['unit']."><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
}
}
This is for displaying the cliked rows from searched products.
$('body').on('click','.js-add',function(){
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
swal("Enter number of item to buy:", {
content: "input",
})
.then((value) => {
if (value == "") {
swal("Error","Entered none!","error");
}else{
var qtynum = parseInt(value);
if (isNaN(qtynum)){
swal("Error","Please input a valid number!","error");
}else{
var total = value * price;
$('#tableData').append("<tr><td>"+barcode+"</td
<td>"+product+"</td>
<td>"+accounting.formatMoney(price,{symbol:"₱",format: "%s %v"})+"</td><td>"+unit+"</td>
<td>"+value+"</td>
<td class='totalPrice'>"+accounting.formatMoney(total,{symbol:"₱",format: "%s %v"})+"</td>
<td><button class='btn btn-danger' type='button' id='delete-row'>&times</button><tr>");
}
}
});
});
I'd tried this code but it return NaN.
$(document).ready(function(){
var TotalValue = 0;
$("#tableData tr").each(function(){
TotalValue += parseFloat($(this).find('.totalPrice').text().replace(/,/g, "₱"));
});
alert(TotalValue);
});
I'd tried modifying the code but I cant get the job done. Hope someone will help about this one. Thanks in advance.
Edit: Updated answer.
Based off what you tried here would be a working solution using your logic.
$(document).ready(function(){
var TotalValue = 0;
var TotalPriceArr = $('.totalPrice').get()
$(TotalPriceArr).each(function(){
TotalValue +=parseInt($(this).text().replace('₱', ''))
});
alert(TotalValue);
});

Populate Table Content with Data From Ajax

I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);

Angularjs checkbox like gmail

Im newbie in angularjs.
Now im having issues with a checkbox.
First: my web are paging , sorting and change page size by call api to get data from server in factory:
this.getData = function(page , sortColumm, sortType , pageSize, searchText){
$http({
method = get;
url = "api/data?page="+page +"&sortColumm=" +sortColumm +"&sortType="+sortType +"&pagesize="+pageSize+"&search="+searchText;
}).success(function (data) {
}).error(function (error) {
});
}
now i have a page using angularjs to bind data using funciton getData.
html:
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()"></th>
<th>Administrator Name</th>
<th >Administrator Type</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="gladmin in gladmins" ng-switch on="gladmin.isEnabled"
on-finish-render="resizetable">
<td><input type="checkbox" ng-model="gladmin.Selected" value="{{gladmin.id}}" ng-click="selectionAdmin(gladmin.id)"></td>
<td>{{gladmin.name}}</td>
<td>{{gladmin.type}}</td>
</tr>
</tbody>
controller
app.controller('adminPage',function(){
// call getData
$scope.checkAll=function(){
// what should i write here?
// i want check all is for current page, next page checkall = fall,
// same GMAIL
}
$scope.selectionAdmin = function(id){
// what should i do here
}
})
All i want is the checkall same the checkall in gmail ? anyone help me ? please, i am new bie in this!
i find some link here : http://plnkr.co/edit/N98IKTcHoZMCs18FjSRF?p=preview
http://vitalets.github.io/checklist-model/
but it work not same i want !
It is hard for me to understand the question but I think you just want a property of ng-checked="isAllChecked" in your ng-repeat for the inputs. When that value is set to true all of them should check.

AngularJS: on-click hide active table and show new one?

I have an html table, and when I click on any row new table shows with more specific information about some row data. I am using ng-click, ng-repeat and ng-show. Here is what I am trying to achieve: I want to do so, when I click on some row, the table shows and when I click on the same row again the table hides and also when some row is active, if you click on another row the first table hides and the new shows. Here is my html:
<tbody>
<tr ng-repeat-start="car in carList | filter:tableFilter" ng-click="modelRow.activeRow = car.name; car.showDetails = !car.showDetails">
....
</tr>
<tr ng-repeat-end ng-show="modelRow.activeRow==car.name && car.allReviews.length!=0 && car.showDetails" class="hidden-table">
<td colspan="6">
<table class="table table-striped table-bordered table-condensed table-hover">
<tbody ng-repeat="rev in car.allReviews">
....
</tbody>
</table>
</td>
</tr>
</tbody>
Here is my controller:
carApp.controller("TableBodyCtrl", function($scope){
$scope.modelRow = { activeRow: '' };
$scope.carList = [{"name":"Ford Focus hatchback",...,"showDetails":false}...];
And initially my "showDetails" in every object in my $scope.carList array is set to false.
Then as you can see in my html I do ng-click="modelRow.activeRow = car.name; car.showDetails = !car.showDetails".
It works fine, but when I click, for example, on "Volkswagen Golf" row then on "Ford Focus hatchback" and then again on "Volkswagen Golf" row, the table would not show up.
It is happening because when I click a bit on any rows "showDetails" values in $scope.carList array are set to true not false value.
How can I fix this issue or what the alternative way to achieve my goal?
Note: also I need a solution that will not slow my website, (my $scope.carList array have hundreds of cars)
make 'showDetails' a global variable not related to car.
make function for ng-click="func(car)".
$scope.func = function(car) {
if (!$scope.showDetails) {// open info
$scope.showDetails = true;
} else if ($scope.modelRow.activeRow = car.name && $scope.showDetails) {
// info was opened for, closing
$scope.showDetails = false;
} else { //info was opened, we open new one
$scope.showDetails = true;
}
$scope.modelRow.activeRow = car.name;
}

Categories