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>
Related
I am using Ajax request to fetch data from database. All I want to do is to display the result in tabular form whenever we select an option from the option list. I am also able to do that but when I am choosing another option the view for the previous option it is not removed from the table.
View:
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
Controller:
public function getBranchDetail(){
$branch = array();
$city_id = $this->input->post('city_id');
if($city_id){
$con['conditions'] = array('id'=>$city_id);
$branchData = $this->Bank_model->getBranchData($con);
}
echo json_encode($branchData);
}
Model:
function getBranchData($params = array()){
$this->db->select('c.micr_code, c.ifsc_code, c.contact_no, c.address');
$this->db->from($this->branchTbl.' as c');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('c.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
When I am selecting a city from option it is showing me the result for that city which is correct. When I am choosing another city from the option it is showing the result also, but the result for the previous option is not removed from the table. I want to remove the previous record when I am selecting another option.
Check the below code ( not tested ). Clear the contents before appending data in the loop.
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
// clear the data before appending
$('#ifsc').html("");
$('#micr').html("");
$('#contact').html("");
$('#address').html("");
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
I'm not looking to add to / append an existing table. My table is empty until results are returned via AJAX. I'm trying to sort my tables data via the javascript plugin, tablesorter.js.
I have sorted my table so It's split between header and body. I can't seem to get the table rows to change though
My Code for the AJAX is;
<script>
$(document).ready(function()
{
$("#results").tablesorter();
}
);
</script>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#to_date").datepicker();
});
var to_date = $('#to_date').val();
$( "#genre" ).val();
{
var value = $(this).val();
$( "#price" ).val();
{
var value = $(this).val();
$('#filter').click(function(){
var to_date = $('#to_date').val();
var request = $("#genre").val();
var request1 = $("#price").val();
var data = 'to_date'+'request'+'request1';
if(to_date != '' )
{
$.ajax({
url:"filter.php",
method:"POST",
data: { to_date:to_date, request:request,request1:request1 },
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
});
}
else
{
alert("Please Select Date");
}
});
};
};
});
</script>
and my code for the html / PHP is;
<table id="results" class="tablesorter">
<thead>
<tr>
<th>Event</th>
<th>Venue</th>
<th>Genre</th>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["event_name"]; ?></td>
<td><?php echo $row["venue_name"]; ?></td>
<td><?php echo $row["genre"]; ?></td>
<td><?php echo $row["event_date"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
you never actually called to the plugin:
$("results").tablesorter()
Everytime you get your data updated you should make a all to the tablesorters update trigger so it gets its references updated.
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
that should do the trick
I am doing a project for my school subject. I am confused on how to do checking data's in checkbox and when I press a submit button, it will loop to insert into my database. I manage to display/alert the data that is being checked in my data-table.
Here is my Contoller where it populates my data table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is in my view:
<div class="dataTable_wrapper">
<table id="dataTables-docs" class="table table-striped table-bordered table-hover dataTable dtr-inline" role="grid" style="width: 100%;" width="100%" aria-describedby="dataTables-material">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- dataTable_wrapper -->
here is my javascript to echo the selected check box from my data-table:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
now, i want to all that is being checked to be inserted in my database like this:
(myid,selectedfromcheckbox);
here is my screenshot from database table:
Use another ajax to insert the data
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
$.ajax({
type:"post",
data: {user_id:user_id},
"url": "<?php echo site_url('admin_controls/saveData')?>",
success:function(data){
$("#info").html(data);
}
});
});
// Below code in you controller
public function saveData()
{
// code to save in controler
}
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?!
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.