how to filter dates with angular? - php

I'm building a project with angular and php. I have a "select" option where I choose specific date and it shows me all details in a table, and counting on several things and everything works great. but when I pick a date, i want it to show all results by specific month and not by specific date(for example --> now i choose date like this - '2016-4-15' it will give me all information specific to this date and not by month like i need). can someone please help? in my database the 'date' value is date.
Php query :
$query=" SELECT `description` ,`total_price` , `name`,`supplier_id`,`date` FROM `suppliers`,`expenses`
where `supplier_id` = `refer_supplier_id` ";
Html:
<select ng-model="supplierExpenses.selectedOption" ng-change="setTotals(supplierExpenses)"
ng-options = "item.date for item in supplierExpenses |
unique:'date'" >
<option value="">בחר תאריך</option>
</select>
<div class="table-responsive">
<table class="customer-list table table-striped" >
<thead>
<tr >
<th class="Column-Header">מספר ספק</th>
<th class="Column-Header">שם ספק</th>
<th class="Column-Header">כמות מוצרים שנקנו</th>
<th class="Column-Header">מחיר הוצאה</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in supplierExpenses" ng-if = "item.date == supplierExpenses.selectedOption.date"
>
<td>{{item.supplier_id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.total_price}}</td>
</tr>
</tbody>
<tfoot>
<tr class="bg-warning">
<td><font size="6">סה"כ הוצאות</font></td>
<td><font size="6">{{totalExpenses}}</font></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
Controller:
"use strict";
angular.module('dataSystem').controller('supplierExpensesCtrl', function ($scope, $route, $location, $http) {
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data));
$scope.supplierExpenses = arr;
})
// This will log you the error code and trace, if there is an error.
.catch(function(err) {
console.log('err', err)
});
$scope.totalExpenses = 0;
$scope.setTotals = function(totalItem){
$scope.totalExpenses = 0;
for(var item =0; item< totalItem.length; item++){
// console.log(totalItem[item]);
if (totalItem[item] && (totalItem[item].date == $scope.supplierExpenses.selectedOption.date)){
$scope.totalExpenses += parseInt(totalItem[item].total_price);
}
}
}
});

Hi glad you succeed with the total ^^ I edit my answer with the working solution for the date issue
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data)), month, date;
for(var i = 0; i< arr.length; i++){
date = new Date(arr[i].date); //we convert the string into javascript date
month = date.getMonth()+1;
if(month.length === 1){
month = '0'+month; //we add a 0 if needed
}
var year = date.getFullYear();
arr[i].date = month+'/'+year; //we use only the month and year
}
$scope.supplierExpenses = arr;
})

Related

Angular Function suddenly won't working after Using Jquery Ajax

I'm still new to php programming and I'd like to understand why my Angular Function stopped working when I'm using my jquery ajax method post where I update values on my database.
Here is my code on my angular on html:
<tfoot ng-app="kembalianApp" ng-controller="kembalianCtrl">
<tr>
<th class="has-text-right" colspan="6">TOTAL : </th>
<th class="has-text-right" ><p ng-model="total" ng-init="total='<?php echo $record2['total'];?>'"><?php echo $total;?></p></th>
</tr>
<tr>
<th class="no-border has-text-right" colspan="6">BAYAR : </th>
<th style="max-width:100px;padding:0" class="no-border"><input type="text" class="input has-text-right has-text-weight-bold" ng-model="bayar"></th>
</tr>
<tr>
<th class="no-border has-text-right" colspan="6">KEMBALIAN : </th>
<th class="no-border has-text-right">{{kembalian()}}</th>
</tr>
</tfoot>
and this is how my angular code
var app = angular.module('kembalianApp', []);
app.controller('kembalianCtrl', function ($scope) {
$scope.kembalian = function () {
if (parseInt($scope.bayar - $scope.total) >= 0) {
return $scope.result = parseInt($scope.bayar) - parseInt($scope.total);
} else {
return $scope.result = '-';
}
};
});
and this is my Jquery ajax code
$(document).ready(function () {
$('.kurang').on('click', function () {
var id_pesanan = $(this).data('id_pesanan');
var id_makanan = $(this).data('id_makanan');
var jumlah = $(this).data('jumlah');
jumlah = parseInt(jumlah);
jumlah = jumlah - 1;
$.post('assets/ajax/kurangmenu.php', {
id_makanan: id_makanan,
id_pesanan: id_pesanan,
jumlah: jumlah
}, function (data) {
$('#containerpesanan').html(data);
});
});
$('.tambah').on('click', function () {
var id_pesanan = $(this).data('id_pesanan');
var id_makanan = $(this).data('id_makanan');
var jumlah = $(this).data('jumlah');
jumlah = parseInt(jumlah);
jumlah = jumlah + 1;
$.post('assets/ajax/kurangmenu.php', {
id_makanan: id_makanan,
id_pesanan: id_pesanan,
jumlah: jumlah
}, function (data) {
$('#containerpesanan').html(data);
});
});
});
I don't get why my angular wont work after I use jquery ajax.
Here is the error in your AngularJS code: -
<p ng-model="total" ng-init="total='<?php echo $record2['total'];?>'"><?php echo $total;?></p>
ng-model is working for two-way binding. p tag is not supported for ng-model. if you want to bind p tag then you can use ng-bind or {{}}.
<p ng-bind="total"></p>
or
<p {{::total}}></p>

Showing data table inside a table with ng-repeat (angularjs, html)

Im having troubles with showing the data that i want in the tables. I did the following sketch so you guys can figure out what i want to display:
The query i have in my php/mysql connector brings me each "Tarea" data(second table) with "proyecto" and "alerta" but i need to display "proyecto" and "alerta" only 1 time per row.
So i did this in angular to storage the data of the second table(Tarea, Termino, Estado, Nombre), while i display the data of the first table.
scope.llamada1 = function() {
$http.get("conector.php?tipoDato=query1")
.then(function(response) {
$scope.mensajeEspera = "";
$scope.datos1 = response.data;
for(var i = 0; i < $scope.datos1.length; i++){
var currentObj = $scope.datos1[i];
$scope.datos1[i].detalleProyecto = [{
"tarea":currentObj.tarea ,
"fecha_termino":currentObj.fecha_termino ,
"estado":currentObj.estado,
"nombre_completo":currentObj.nombre_completo}];
}
});
}
And in the html i get the data like this, with the table inside the last :
<table id="tablaTareas" class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Proyecto</b></td>
<td><b>Alerta</b></td>
<td><b>Tareas</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in datos1 ">
<td style="vertical-align: top;">{{x.proyecto}}</td>
<td style="vertical-align: top;">{{x.alerta}}</td>
<td style="vertical-align: top;">
<table class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Tarea</b></td>
<td><b>Termino</b></td>
<td><b>Estado</b></td>
<td><b>Responsable</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="y in x.detalleProyecto track by $index">
<td>{{y.tarea}}</td>
<td>{{y.fecha_termino}}</td>
<td>{{y.estado}}</td>
<td>{{y.nombre_completo}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
But is repeating "Proyectos" and "Alerta" and displaying 1 "Tarea" per row and not every task together per proyect and alert, an example below.
you should try to arrange your data this way
[
{
name: nombre_completo,
data: [
{
tarea,
fecha_termino,
estado
}
]
}
]
where name is the repeated data that you don't want to repeat
a little example
if you have data like
[{country: Chile, name: Martin},{country: Chile, name: Nico},{country: Peru, name: Seba},{country: Peru, name: Nicole},{country: Argentina, name: Warencita}]
try this (assuming var datos is where your data is stored)
var datos = [{country: 'Chile', name: 'Martin'},{country: 'Chile', name: 'Nico'},{country: 'Peru', name: 'Seba'},{country: 'Peru', name: 'Nicole'},{country: 'Argentina', name: 'Warencita'}]
var temp = []
var exists
var place
for(var i = 0; i < datos.length; i++){
exists = false;
for(var k = 0; k < temp.length; k++){
if(datos[i].country === temp[k].country){
exists = true;
place = k;
break;
}
}
if(exists){
temp[place].data.push({
name: datos[i].name
})
}else{
temp.push({
country: datos[i].country,
data: [{
name: datos[i].name
}]
})
}
}

Permanently change order of records by draggable table

I have data table that populates data from the database, I'm using an Ajax Call to Populate the data on the table and I'm using jQuery RowSorter.js to make my table rows draggable. The my query in my data is sorted by sortorder column. Provided that it is draggable, how can I make the sort permanent in the table and be saved on the database. The sortorder should also be updated depending on what sort order the user choose in the draggable table rows. Here's my code:
Ajax:
$.ajax({
url: "api/question/all",
type: 'GET',
success: function(result){
var myObj = $.parseJSON(result);
$.each(myObj, function(key,value) {
var t = $('#QuestionList').DataTable();
t.row.add( [
value.id,
value.columnheader,
value.costperlead,
// value.isenabled,
"<label class='toggle'><input type='checkbox' checked='' id='"+value.columnheader+"'><span class='handle'></span></label>",
value.sortorder,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('question').'/';?>"+value.id+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('question').'/';?>"+value.id+"' accept-charset='UTF-8' class='pull-left' >"+
"<input name='_method' type='hidden' value='DELETE'>"+
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>"+"</form>",
] ).draw();
if(value.isenabled == "Yes")
{
$("#"+value.columnheader).prop('checked', true);
}
else if(value.isenabled == "No")
{
$("#"+value.columnheader).prop('checked', false);
}
});
}}).error(function(){
progress.progressTimer('error', {
errorText:'ERROR!',
onFinish:function(){
alert('There was an error processing your information!');
}
});
}).done(function(){
progress.progressTimer('complete');
$( "#progressbar" ).fadeOut( "slow" );
});
My Table HTML
<table id="QuestionList" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="5"> <center>Question Information<center></th>
<th colspan="2"> <center>Actions<center></th>
</tr>
<tr>
<th>ID</th>
<th>Column Header</th>
<th>Cost Per Lead</th>
<th>Is Enabled?</th>
<th>Sort Order</th>
<th>Edit/View</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7"> </td>
</tr>
</tfoot>
</table>
JS to Call rowsorter
$("#QuestionList").rowSorter({
onDrop: function(tbody, row, index, oldIndex) {
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
}
});
My Query
public function apiGetQuestions()
{
$questions = Question::orderBy('id', 'DESC')->get();
return json_encode($questions);
}
I'm using Laravel 5, any ideas or guides will be appreciated. Thanks!
Update:
Using Jquery's rowsorter function I can keep track of the positions of the rows and its new position:
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
You don't want to store the entire table, but you can store the sorting events. Everytime a user clicks on a column, you add that to a sort sequence array and save the array serialized.
var sortSequence = [];
$('th').click(function() {
// direction: 'asc' or 'desc'
sortSequence[$(this).text()] = get_direction_from_jquery_sort_plugin_somehow();
var data = {
'table': ...,
'sequence': sortSequence.serialize()
};
$.post('store-sequence', data);
});
I would then have some sanitization in place when storing the sorting to remove any duplication or ascending, descending, ascending sequences.
Then when retrieving the data, you add the sorting sequence as orderBy() calls.
$query = \DB::table("my_table")->where(...);
$sorts = $this->fetchSorting(\Auth::user(), "my_table");
foreach ($sorts as $column => $direction) {
$query->orderBy($column, $direction);
}
This is all a lot of work however and I wonder if it is really worth it.

Get the sum value of selected check boxes on check box click with jquery after ajax response

I need to get the sum value of selected check boxes on check box click with jquery after ajax response.
$('.check:checked').each(function() { });
The above jQuery function works if I call the check box when the page loading
but I have to call this function after an AJAX response it's not working.
So I have tried with below one but no idea to get the sum of the selected check boxes value
$('body').on('click', '.check', function(){ }
jQuery function
<script>
$(document).ready(function(){
$('body').on('click', '.check', function(){
var tot = 5;
$('.check:checked').each(function() {
console.log($(this).val());
tot += $(this).val();
});
console.log(tot);
});
$('#payType').change(function(){
var pType = $(this).val();
var y = $('[name = "year"]').val();
clearRuntimeFunctions();
$('#payType').val(pType);
if(pType != "dntSntReqst"){
$('#ajax_img_lod').show();
$.ajax({
url: 'AJAX_Requst/getOtherPaymt.php',
type: 'POST',
data: {
'pYear': y,
'payType': pType,
},
success: function( data ){
$('#ajax_img_lod').hide();
$('#ajax_response').html(data);
}
});
}
});
});
</script>
This an AJAX response page
<?php
<table class="table table-message" style="margin: 10px 25px;max-width: 350px;">
<tbody>
<tr class="heading">
<td class="cell-title"> Year </td>
<td class="cell-title"> Month </td>
<td class="cell-title"><div align="right"> Amount </div></td>
<td class="cell-title"><div align="right"> Balance</div> </td>
<td class="" width="2%"><div align="right"></div></td>
</tr>
foreach($monthEnd_Arry as $m)
{
$sql_cls = mysql_query("SELECT book FROM cls_room_tb WHERE cls_brnch_id='$br_id' AND start_date <= '$m'");
$noCls = mysql_num_rows($sql_cls);
if ($noCls > 0) {
if ($noCls <= 4) {
$centFee = $noCls * 1000;
}
else {
$centFee = 4 * 1000;
$centFee += ($noCls - 4) * 500;
}
$sql_paid = mysql_query("SELECT SUM(amount) FROM other_payments WHERE br_id='$br_id' AND pay_type='$payType' AND
pYear = '$pYear' AND pMonth='". substr($m , 5, 2)."'");
$res_paid = mysql_fetch_row($sql_paid);
$paidAmount = $res_paid[0];
$amount = $centFee ;
echo '<tr class="unread">
<td class="cell-title" >'.$pYear.'</td>
<td class="cell-title" >'.month_crt( substr($m , 5, 2)).' - '.$noCls.' </td>
<td class="cell-title" >
<div align="right"> '.numFormt($amount).'</div>
</td>
<td class="cell-title" ><div align="right">'.numFormt( $amount - $paidAmount ).'</div></td>
<td class="cell-title" >
<input type="checkbox" class="check" name="checkPay[]" value="'.numFormt( $amount - $paidAmount ).'" />
</td>
</tr>';
}
}
?>
Sum it up inside ajax success callback, e.g:
$.ajax({
url: 'AJAX_Requst/getOtherPaymt.php',
type: 'POST',
data: {
'pYear': y,
'payType': pType,
},
success: function (data) {
$('#ajax_img_lod').hide();
$('#ajax_response').html(data);
// find(':checked') for checked ones
// even none seems checked regarding your servser side script
// so maybe use `.find('.check')` instead but that's not clear what you are expecting here???
var sum = $('#ajax_response').find(':checked').map(function () {
return +this.value
}).get().reduce(function (a, b) {
return a + b;
});
// do whatever you want with `sum`
console.log(sum);
}
});
Or maybe you want to call it on:
$(document).on('change', '.check', function () {
var sum = $('.check').filter(':checked').map(function () {
return +this.value
}).get().reduce(function (a, b) {
return a + b;
}/* to start with default value != 0 as '5' in your posted code*/, 5);
// do whatever you want with `sum`
console.log(sum);
}
In fact, i'm not sure to understand what is your expected behaviour. How/when do you wish to sum up checked checkboxes values?!

Calling a JS scipt to run a php file and then post html to the relative row

Follow this if you can...
Basically i have an order form (which begins with one row).
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
<a id="add">+</a>
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">Product Code (e.g 66203)</td>
<td width="33%">Mtrs Required (e.g 10)</td>
<td width="33%">Preview Image</td>
</tr>
<tr class="item">
<td class="prodcode"><input type="text" name="prodcode[]" id="prodcode" /></td>
<td class="meterage"><input type="text" name="meterage[]" id="meterage" /></td>
<td class="imgsample"></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
Notice the link with an ID of "add". When checked this adds a new row to the table with the same ID. Using the code below.
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last input').val('');
$('td.imgsample:last a').remove();
return false;
});
//Check for image preview
$("#prodcode").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.imgsample') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var imgsample = $this.closest('tr').find('td.imgsample')
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
});
My PHP in searchimage...
When i currently enter a product code if it is invalid it only puts the productID in td.imsample and i want it to say INVALID CODE
//Find image based on Product Code
function findimage($imageToFind) {
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = ".strtoupper($imageToFind)."";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0) {
$sql2 = "SELECT * FROM imageindex WHERE filename LIKE '".strtoupper($imageToFind)."-%'";
$stmt2 = $dbh->query($sql2);
$obj2 = $stmt2->fetch(PDO::FETCH_OBJ);
echo ($stmt2->rowCount() == 1 ? '<span>'.$obj2->path.'/'.$obj2->filename.'</span> -' : 'No Image Available');
} else {
echo 'Invalid Code';
}
}
//Call Function
findimage($_POST['imgreference']);
try this, can have code errors since I could not test at all:
jQuery Template
HTML:
<script id="template-item" type="text/x-jquery-tmpl">
<tr class="item" id="${id}">
<td class="prodcode"><input type="text" name="prodcode[]" class="prodcode-input" data="${id}" val="" /></td>
<td class="meterage"><input type="text" name="meterage[]" class="meterage-input" val="" /></td>
</tr>
</script>
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
+
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<thead>
<tr>
<th width="33%">Product Code (e.g 66203)</th>
<th width="33%">Mtrs Required (e.g 10)</th>
<th width="33%">Preview Image</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td class="imgsample"></td>
</tfoot>
</table>
<button>Submit</button>
</form>
JS:
$(function() {
var counter = 0;
//Check for image preview
var blur_event = function(ev) {
var
self = $(this),
imgsample = $("#ordertable tfoot .imgsample");
$(imgsample).html( $(this).class() ); // update the contents
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(self).val() },
function(data) {
$(imgsample).html(data);
}
);
return false;
};
//Order Form
$("#add").bind("click", function(ev) {
counter++;
var cln = $('#template-item').tmpl({id:"item-"+counter);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
$(cln).find(".prodcode-input").bind("blur", blur_event);
$(cln).appendTo('#ordertable tbody');
return false;
});
});
Your problem is most likely due to the duplicated ID. That makes your HTML document invalid. See my explanation here.

Categories