Codeigniter MySQL update - mysql

I have MySQL database used with Codigniter including following table too.
+-------------------+-----------------+------+-------+--------+
| update_request_id | update_stock_id | item | r_qty | status |
+-------------------+-----------------+------+-------+--------+
And used the following for loop in Controller, to update records in the table.
$count = count($this->input->post('item_id'));
$items = $this->input->post('item_id');
$qts = $this->input->post('qty');
for ($x = 0; $x < $count; $x++) {
$udetails[$x]['update_stock_id'] = $id;
$udetails[$x]['item'] = $items[$x];
$udetails[$x]['r_qty'] = $qts[$x];
$udetails[$x]['status'] = 1;
}
And the following View used to get relevant values for the controller.
<?php
if(!empty($itemReqFromHD)){
$newMaster=$itemReqFromHD[0];
}
?>
<script type="text/javascript">
$(document).on("change", "#item", function () {
$.ajax({
'url': '<?=site_url("item/isExistProduct/?q=")?>' + $('#item').val(),
'method': 'GET',
'success': function (data) {
//console.log(data);
var jData = JSON.parse(data);
if (jData.status == true) {
$('#request_table').append('<tr>' +
'<td ><span id="product" >' + jData.data[0].item_name + '</span>' +
'<input type="hidden" id="item_id[]" name="item_id[]" value="'+jData.data[0].item_id+'">' +
'</td>' +
'<td class="text-center"><input class="form-control" autofocus required type="number" step="any" id="qty['+jData.data[0].item_id+']" name="qty['+jData.data[0].item_id+']" ></td>' +
'<td class="text-center" ><i class="fa fa-remove remove" style="cursor: pointer"></i></td>' +
'</tr>');
}
},
'error': function () {
}
});
});
$(document).on("click", ".remove", function () {
$(this).closest('tr').remove();
});
</script>
<div class="box box-info">
<div class="box box-info collapsed-box">
<div class="box-header with-border">
<h3 class="box-title">Update Item Request From HD</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" style="font-size: 16px;" data-widget="collapse"><i
class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body" style="display: block">
<form action="<?= site_url('item/editItemReqFromHD/'.$newMaster->update_stock_id) ?>" method="post">
<div class="row">
<div class="col-md-3">
<div class="form-group"><label>Request Date</label>
<input type="date" name="request_date" id="request_date" class="form-control" value="<?=$newMaster->billed_date?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group"><label>Select Product</label>
<select name="item" id="item" class="form-control select2" >
<option value="">Select Product</option>
<?php
if (!empty($products)) {
foreach ($products as $row) {
?>
<option value="<?= $row->item_id ?>"><?= $row->item_name ?></option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
<!--table-->
<div class="col-md-12 column">
<div class="col-md-12">
<div class="control-group table-group">
<label class="table-label">Request Items *</label>
<div class="controls table-controls">
<table id="request_table"
class="table items table-striped table-bordered table-condensed table-hover">
<thead>
<tr style="background-color: #3c8dbc">
<th class="col-md-8">Product Name</th>
<th class="text-center" class="col-md-2">Quantity</th>
</th>
<th style="width: 30px !important; text-align: center;">
<i class="fa fa-trash-o" style="opacity:0.5; filter:alpha(opacity=50);"></i>
</th>
</tr>
</thead>
<tbody>
<?php
foreach ($itemReqFromHD as $row){
?>
<tr>
<td ><?=$row->item_name?>
<input type="hidden" id="item_id[]" name="item_id[]" value="<?=$row->item_id?>">
</td>
<td class="text-center"><input class="form-control" value="<?=$row->r_qty?>" required type="number" step="any" id="r_qty[<?=$row->item_id?>]" name="r_qty[<?=$row->item_id?>]" ></td>
<td class="text-center"><i class="fa fa-remove remove" style="cursor: pointer"></i></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary btn-block">Update Request</button>
</div>
</div>
</form>
</div>
</div>
</div>
All codes are working fine but at the time of the update the column 'r_qty' is not edited, leaving the table as follows:
Array
(
[0] => Array
(
[update_stock_id] => 577
[item] => 2
[r_qty] =>
[status] => 1
)
[1] => Array
(
[update_stock_id] => 577
[item] => 4
[r_qty] =>
[status] => 1
)
)
I could not catch what I am going wrong ? Can anyone help me ?

Related

Table and Array filtering/pipe

i'm trying to pipe the values of my table to show only the things i want, actually with "EMPRESAS", "TIPO USUARIO"; it's working(with some errors but i will study on my own to fix that). But with status i get the return of how many "ATIVOS", and "INATIVOS" i got, but when i trying to list him in the table, in my ATIVOS appear the INATIVO, how to fix that? i thing its something happening because inATIVOS and ATIVOS had commun chars, btw i don't know how to fix that
<div class="row">
<div class="col-md-12">
<app-card cardTitle="Informe os parâmetros da pesquisa">
<form (ngSubmit)="onSubmit(selectVal.value, selectedOption)">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class=" form-label"
style="font-weight: bold;"
>Filtrar pesquisa</label>
<select class="form-control" #selectVal name="filterOption" formControlName="filterOption">
<option value="TODOS">TODOS</option>
<option value="empresa">EMPRESAS</option>
<option value="tipo_usuario">TIPO DO USUÁRIO</option>
<option value="status">STATUS DO USUÁRIO</option>
</select>
</div>
</div>
<div
*ngIf="selectVal.value == 'empresa'"
class="var-select" class="col-md-2">
<div class="form-group">
<div >
<label class="form-label"
style="font-weight: bold">Empresa</label>
<select class="form-control" name="empresa" [(ngModel)]="selectedOption" >
<option *ngFor="let usuario of usuarios | pEmpresa : selectedOption" value={{usuario.empresa}}> {{usuario.empresa}}</option>
</select>
</div>
</div>
</div>
<div
*ngIf="selectVal.value == 'tipo_usuario'"
class="var-select" class="col-md-2">
<div class="form-group">
<div>
<label class="form-label" style="font-weight: bold">Tipos do usuário</label>
<select class="form-control" name="tipo_usuario" [(ngModel)]="selectedOption">
<option *ngFor="let usuario of usuarios | pTipo : selectedOption " value={{usuario.tipo_usuario}}>{{usuario.tipo_usuario}} </option>
</select>
</div>
</div>
</div>
<div
*ngIf="selectVal.value == 'status'"
class="var-select" class="col-md-2">
<div class="form-group">
<div >
<label class="form-label" style="font-weight: bold">Status dos usuários</label>
<select class="form-control" name="status" [(ngModel)]="selectedOption">
<option *ngFor="let usuario of usuarios | pStatus : selectedOption" value={{usuario.status}}>{{usuario.status}}</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-warning pos">CONSULTAR</button>
</div>
</div>
</div>
</form>
</app-card>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-success" (click)="cadastrarNovoUsuario()">Cadastrar Usuario</button>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12" *ngIf="carregar_lista_usuarios">
<app-card cardTitle="Usuários" cardClass="card-datatable" [options]="false">
<div class="table-responsive col-md-12">
<table datatable [dtOptions]="dtResponsiveOptions" class="table table-striped table-bordered table-hover" >
<thead>
<tr>
<th style="visibility: hidden; width: 1%; border-collapse: inherit; border-color: transparent;"></th>
<th>NOME</th>
<!-- <th>UID</th> -->
<th>EMPRESA</th>
<th>E-MAIL</th>
<th>TELEFONE</th>
<th>STATUS</th>
<th>AÇÃO</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let usuario of usuarios | filter : selectedOption">
<div class="imagem text vasco" style="border-radius: 80%; height: 60px; border-color: transparent;" ><img
[src]="usuario.imagem_url == '' || usuario.imagem_url == 'null' ? asset : usuario.imagem_url" class="img-radius align-center" style="width:45px"></div>
<td class="text" style="width: 5%; max-width: 4.8rem;">{{usuario.nome_usuario}}</td>
<!-- <td style="width: 1%;">{{usuario.uid}}</td> -->
<td class="text" style="width: 11%; max-width: 5.7rem">{{usuario.empresa}}</td>
<td class="text" style="width: 10%; max-width: 10.9rem">{{usuario.email}}</td>
<td mask="(00)0 0000 0000" class="text" style="width: 10%; max-width: 4rem">{{usuario.celular}}</td>
<td class="text" style="width: 10%; max-width: 3rem">{{usuario.status}}</td>
<td class="text" style="width: 10%;">
<button type="submit" class="btn btn-success" (click)="editarUsuario(usuario.uid)"><i class="feather icon-edit"></i></button>
<button *ngIf="adm_op" type="submit" class="btn btn-danger" (click)="apagarUsuario(usuario.uid)"><i class="feather icon-x-circle"></i></button></td>
</tr>
</tbody>
</table>
</div>
</app-card>
</div>
</div>
This is the PIPE i'm using in the HTML
Pipe.TS
#Pipe({name: "pStatus"})
export class PipeStatus implements PipeTransform {
transform(usuarios: Array<Usuario>, selectedOption){
let result = []
let obj = {}
let obj2 = 'status'
console.log("SELECIONADO: " , selectedOption)
usuarios.forEach((item, i) => {
obj[item[obj2]] = i;
console.log("value", item.status)
});
for(let key in obj){
let idx = obj[key]
console.log("IDX", idx, "OBJ for", obj, 'KEY', key)
result.push(usuarios[idx])
}
return result
```

renderAjax failed to return data

I did this in the past year and it works just fine. Until recently I encounter this problem which I don't know what caused it.
Here I'm trying to pass supplierID from a (1)form through (2)ajax javascript and return the (3)data from AdminController to a (4)div in the same view
(1)form:-
<?php $form = ActiveForm::begin([
'id'=>'chatform'
]);?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th>Supplier</th>
<th>Option(s)</th>
</tr>
</thead>
<tbody>
<?php
for($x = 0; $x < count($supplierChatInfoListTable); $x++){ ?>
<tr>
<td>
<?=$x+1?>
<div class="form-group">
<input type="hidden" name="supplierID" id="supplierID" class="form-control"
value="<?=$supplierChatInfoListTable[$x]['supplierID']?>" style="width: 50px">
</div>
</td>
<td >
<h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
</td>
<td>
<button type="button" class="btn btn-primary btnchat"><i class="fa fa-edit"></i></button>
</td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th>No</th>
<th>Supplier</th>
<th>Option(s)</th>
</tr>
</tfoot>
</table>
</div>
<?php ActiveForm::end();?>
and here is my (2)javascript running in the same view:-
<?php
$urproudcode= Url::to(['admin/chatinfo2pass']);
$this->registerJs("
$(function(){
$('.btnchat').click(function(){
var supplierID = $('#supplierID').val();
$.ajax({
'url':'".$urproudcode."',
'data':{supplierID:supplierID},
'method':'POST',
beforeSend: function (xhr) {
$.blockUI({
message: 'Processing...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
},
'success':function(data){
$('.chatmessages').html('Success');
if(data == 'false'){
$.unblockUI();
$('.chatmessages').html('Data False');
}else{
$.unblockUI();
$('.chatmessages').html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.unblockUI();
$('.chatmessages').html('Failed');
console.log(data);
}
});
});
});
");
?>
(3)div with class=chatmessages in the same view
<div class="col-md-8 chatmessages">
</div>
(4)actionChatinfo2pass in AdminController
public function actionChatinfo2pass()
{
$postData = \Yii::$app->request->post('supplierID');
$supplierID = intval($postData);
// fetch all supplier for chat
$supplierChatInfoListTable = SupplierProfile::find()
->select(['supplier_profileID AS supplierID','supplier_profile.first_name AS supplierFirstname',
'supplier_profile.middle_name AS supplierMiddlename', 'supplier_profile.last_name AS
supplierLastname', 'login_profile.login_profileID AS loginID', 'status_login.status_loginID AS
statusLoginID', 'status_login.description AS statusLogindesc'])
->leftJoin('login_profile', 'login_profile.login_profileID = supplier_profile.login_profile_ID')
->leftJoin('status_login', 'status_login.status_loginID = login_profile.status_login_ID')
//->where(['=', 'status_login.description', $activeSupplier])
->orderBy(['supplier_profile.supplier_profileID' => SORT_ASC])
->asArray()
->all();
$dataSend['supplierChatInfoListTable'] = $supplierChatInfoListTable;
$this->layout = 'admin/main';
$html= $this->renderAjax('#app/views/admin/displaychatmessage.php',$dataSend);
echo $html;
}
But it return the 'same' supplierID for both supplier as show below:
and browser console give me this error?(updated):-
btw, this is the content of displaychatmessage.php (I just try to display supllierID and their name)
<!-- DIRECT CHAT WARNING -->
<div class="box box-warning direct-chat direct-chat-warning">
<div class="box-header with-border">
<h3 class="box-title">Direct Chat</h3>
<div class="box-tools pull-right">
<span data-toggle="tooltip" title="3 New Messages" class="badge bg-yellow">3</span>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
<i class="fa fa-comments"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<!-- Conversations are loaded here -->
<div class="direct-chat-messages">
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<?php for($z = 0; $z < count($supplierChatInfoListTable); $z++){?>
<span class="direct-chat-name pull-left">Supplier ID: <?=$supplierChatInfoListTable[$z]['supplierID']?>, <?=$supplierChatInfoListTable[$z]['supplierFirstname']?> <?=$supplierChatInfoListTable[$z]['supplierMiddlename']?> <?=$supplierChatInfoListTable[$z]['supplierLastname']?></span>
<?php }?>
<span class="direct-chat-timestamp pull-right">23 Jan 2:00 pm</span>
</div>
<!-- /.direct-chat-info -->
<img class="direct-chat-img" src="dist/img/user1-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
<div class="direct-chat-text">
Is this template really for free? That's unbelievable!
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">Sarah Bullock</span>
<span class="direct-chat-timestamp pull-left">23 Jan 2:05 pm</span>
</div>
<!-- /.direct-chat-info -->
<img class="direct-chat-img" src="dist/img/user3-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
<div class="direct-chat-text">
You better believe it!
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
</div>
<!--/.direct-chat-messages-->
<!-- Contacts are loaded here -->
<div class="direct-chat-contacts">
<ul class="contacts-list">
<li>
<a href="#">
<img class="contacts-list-img" src="dist/img/user1-128x128.jpg" alt="User Image">
<div class="contacts-list-info">
<span class="contacts-list-name">
Count Dracula
<small class="contacts-list-date pull-right">2/28/2015</small>
</span>
<span class="contacts-list-msg">How have you been? I was...</span>
</div>
<!-- /.contacts-list-info -->
</a>
</li>
<!-- End Contact Item -->
</ul>
<!-- /.contatcts-list -->
</div>
<!-- /.direct-chat-pane -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<form action="#" method="post">
<div class="input-group">
<input type="text" name="message" placeholder="Type Message ..." class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-warning btn-flat">Send</button>
</span>
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
<!--/.direct-chat -->
Can you help me with this? I don't know where it went wrong.
As you have mentioned you are getting same supplierID on clicking both supplier. This problem is caused because in your js code you are getting supplierID by id of the input i.e '#supplierID', and according to your html code the input elements of both of the suppliers have same value in their id attribute i.e 'supplierID', because of that every time js will get value from first input element with id attribute value 'supplierID'. So you need to make some changes in your html and js code. As there is separate edit button for each supplier so instead of using input to store supplierID value you can store it in a data attribute in the edit button. So your updated html code would become
<?php $form = ActiveForm::begin([
'id'=>'chatform'
]);?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th>Supplier</th>
<th>Option(s)</th>
</tr>
</thead>
<tbody>
<?php
for($x = 0; $x < count($supplierChatInfoListTable); $x++){
$supID = $supplierChatInfoListTable[$x]['supplierID']; ?>
<tr>
<td>
<?=$x+1?>
<div class="form-group">
<input type="hidden" name="<?='supplierID'.$supID?>" id="<?='supplierID'.$supID?>" class="form-control"
value="<?=$supID?>" style="width: 50px">
</div>
</td>
<td >
<h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
</td>
<td>
<button type="button" class="btn btn-primary btnchat" data-supplierID="<?=$supID?>"><i class="fa fa-edit"></i></button>
</td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th>No</th>
<th>Supplier</th>
<th>Option(s)</th>
</tr>
</tfoot>
</table>
</div>
<?php ActiveForm::end();?>
And then get the supplierID of clicked supplier from data attribute of button in js. So your js code would become
<?php
$urproudcode= Url::to(['admin/chatinfo2pass']);
$this->registerJs("
$(function(){
$('.btnchat').click(function(){
var supplierID = $(this).attr('data-supplierID');
$.ajax({
'url':'".$urproudcode."',
'data':{supplierID:supplierID},
'method':'POST',
beforeSend: function (xhr) {
$.blockUI({
message: 'Processing...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
},
'success':function(data){
$('.chatmessages').html('Success');
if(data == 'false'){
$.unblockUI();
$('.chatmessages').html('Data False');
}else{
$.unblockUI();
$('.chatmessages').html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.unblockUI();
$('.chatmessages').html('Failed');
console.log(data);
}
});
});
});
");
?>
I hope your problem will be solved.

MySQL Update Batch Process Remove Some Records

I have a program to store some financial values using batch process. Main tables are finance_budget & finance_budget_issue. finance_budget.budget_id = finance_budget_issue.budget_id (1 to many join)
I tried to edit some records using following code
Controller
public function editIssues($id)
{
$this->checkPermissions('edit', 'allocationIssues');
$bc = array(array('link' => 'budget/regIssues', 'page' => 'Allocation Issues'), array('link' => '#', 'page' => 'Edit'));
$meta = array('page_title' => 'Allocation Issues', 'bc' => $bc);
$this->form_validation->set_rules('vote_id', 'Vote', 'required');
$this->form_validation->set_rules('budget_date', 'Budget Date', 'required');
if ($this->form_validation->run() == true) {
$ustock = array(
'vote_id' => $this->input->post('vote_id'),
'budget_date' => $this->input->post('budget_date'),
'ref_no' => $this->input->post('ref_no'),
'usr' => $this->session->userdata('id_user'),
'added_time' => date('Y-m-d h:i:s'),
'budget_status' => 'issues',
'transfer_status' => 'Pending'
);
$count = count($this->input->post('office'));
$offices = $this->input->post('office');
$amount = $this->input->post('amount');
$notes = $this->input->post('notes');
for ($x = 0; $x < $count; $x++) {
$details[$x]['budget_id'] = $id;
$details[$x]['office'] = $offices[$x];
$details[$x]['amount'] = $amount[$x];
$details[$x]['notes'] = $notes[$x];
}
}
if ($this->form_validation->run() == true && $this->Budget_model->editIssuedAllocations($ustock, $details, $id)) {
$this->session->set_flashdata('message', 'Successfully Updated ..!!');
redirect('budget/regIssues');
} else {
$this->data['vote'] = $this->Budget_model->getVote(array('office_id'=>$this->session->userdata('office_id')));
$this->data['office'] = $this->Budget_model->getOffice();
$this->data['issues'] = $this->Budget_model->budgetById($id);
$this->render('budget/editIssues', $meta, $this->data);
}
}
Model
function editIssuedAllocations($ustock,$details,$id)
{
if(!empty($id)){
$this->db->trans_start();
$this->db->update('finance_budget',$ustock,array('budget_id'=>$id));
if($id!=1){
$this->db->where('budget_id', $id);
$this->db->delete('finance_budget_issue');
$this->db->insert_batch('finance_budget_issue', $details);
}
$this->db->trans_complete();
return $this->db->trans_status();
}
return false;
}
View
<?php
if (!empty($purchase)) {
$details = $purchase;
$purchase = $purchase[0];
}
?>
<script type="text/javascript">
$(document).ready(function () {
var i = $('#last').val();
$(".add-new").click(function () {
i++;
// $('.tab_logic').append();
$('#addr' + i).html("<td><a href='javascript:void(0);' id='add-post' class='external add-new'><i style='color: #00C853 !important;' class='fa fa-2x fa-plus-circle'></i></a></td>" +
"<td><select name='office[]' id='office" + i + "' class='select2 form-control' required>" +
"<option value=''></option>" +
<?php
if (!empty($office)) {
foreach ($office as $row) {
?>
"<option value='<?= $row->office_id ?>'><?= addslashes($row->office_name) ?></option>" +
<?php
}
}
?>
"</select></td>" +
"<td><input name='amount[]' type='number' step='any' placeholder='Amount' class='form-control input-md' required></td>" +
"<td><input name='notes[]' type='text' placeholder='Notes' class='form-control input-md'></td>" +
"<td><a href='javascript:void(0);' class='external remove'><i style='color: #dd4b39 !important;' class='fa fa-2x fa-minus-circle' id='addIcon'></i></a></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
$('#i').val(i);
// alert($('#i').val());
$('#item' + i).select2();
});
$(document).on("click", ".remove", function () {
var count = $('#tab_logic>tbody').children().length;
if (count > 0) {
$(this).closest('tr').remove();
}
});
});
</script>
<div class="box box-info">
<div class="box box-info collapsed-box">
<div class="box-header with-border">
<h3 class="box-title">Edit Issued Allocations</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" style="font-size: 16px;" data-widget="collapse"><i
class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body" style="display: block">
<form action="<?= site_url('budget/editPurchase/' . $purchase->budget_id) ?>" method="post">
<div class="row">
<div class="col-md-2">
<div class="form-group"><label>Budget ID</label>
<input type="text" name="budget_id" id="budget_id" class="form-control" disabled
value="<?= $purchase->budget_id ?> ">
</div>
</div>
<div class="col-md-4">
<div class="form-group"><label>වැය ශීර්ෂය</label>
<select name="vote_id" id="vote_id" class="form-control select2" required>
<option value="<?= $purchase->vote_id ?>"><?= $purchase->vote ?></option>
<?php
if (!empty($vote)) {
foreach ($vote as $row) {
?>
<option value="<?= $row->vote_id ?>"><?= $row->vote ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group"><label>යොමු / ගොණු අංකය</label>
<input type="text" name="ref_no" id="ref_no" class="form-control"
value="<?= $purchase->ref_no ?>">
</div>
</div>
<div class="col-md-2">
<div class="form-group"><label>දිනය</label>
<input type="date" name="budget_date" id="budget_date" class="form-control"
value="<?= $purchase->budget_date ?>">
</div>
</div>
</div>
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr>
<th class="text-center">
</th>
<th class="text-center">
Office
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Notes
</th>
<th class="text-center">
</th>
</tr>
</thead>
<tbody>
<?php
//dd($details);
$x = 0;
foreach ($details as $i => $values) {
// foreach ($values as $key => $value) {
$x = $i;
?>
<tr id='addr0'>
<td>
<a href="javascript:void(0);" id="add-post" class="external add-new"><i
style="color: #00C853 !important;"
class="fa fa-2x fa-plus-circle"></i></a>
</td>
<td style="width: 50%">
<input type="hidden" name="i" id="i" value="<?= $i ?>">
<select name="office[]" id="<?= "office" . $i ?>" class="form-control select2" required>
<option value="<?= $details[$i]->office_id ?>"><?= $details[$i]->office_name ?></option>
<?php
if (!empty($office)) {
foreach ($office as $row) {
?>
<option value="<?= $row->office_id ?>"><?= $row->office_name ?></option>
<?php
}
}
?>
</select>
</td>
<td>
<input type="number" name='amount[]' placeholder='Amount' class="form-control"
value="<?= (-1) * $details[$i]->amount ?>" required/>
</td>
<td>
<input type="text" name="notes[]" placeholder='Notes'
value="<?= $details[$i]->notes ?>" class="form-control"/>
<input type="hidden" name="table_id"
value="<?= $details[$i]->notes ?>">
</td>
<td><a href='javascript:void(0)' class='external remove'><i
style='color: #dd4b39 !important;'
class='fa fa-2x fa-minus-circle ' id='addIcon'></i></a>
</td>
</tr>
<tr id='addr1'></tr>
<?php
//print " $key => $value\n";
// }
//print "}\n";
}
?>
</tbody>
</table>
</div>
<!--table-->
<div class="row">
<div class="col-md-8"></div>
<div class="col-md-4">
<input type="hidden" value="<?= $x ?>" name="last" id="last">
<input type="submit" value="Update" class="btn btn-primary btn-block">
</div>
</div>
</form>
<!--end of table-->
</div>
</div>
</div>
Desired Output
Should be edit some values in the finance_budget & finance_budget_issue tables that related with same budget_id (Eg:- budget_id =2995)
Error
After editing some values in my view that is working & save properly. When I press the save button in my view without editing any value, the record in finance_budget_issue table that is related to finance_budget table by budget_id is deleted.
I can not understand what I am going wrong ? Can anyone help me ?
You could modify the model to check whether $details are empty or not to leave the finance_budget_issue table intact :
function editIssuedAllocations($ustock,$details,$id)
{
if(!empty($id)){
$this->db->trans_start();
$this->db->update('finance_budget',$ustock,array('budget_id'=>$id));
if($id!=1 && !empty($details[0])){
$this->db->where('budget_id', $id);
$this->db->delete('finance_budget_issue');
$this->db->insert_batch('finance_budget_issue', $details);
}
$this->db->trans_complete();
return $this->db->trans_status();
}
return false;
}
I have modified the for loop as follows in the controller.
$count = count($this->input->post('office'));
$offices = $this->input->post('office');
$votes = $this->input->post('vote_id');
$amount = $this->input->post('amount');
$notes = $this->input->post('notes');
$bdate = $this->input->post('budget_date');
for ($x = 0; $x < $count; $x++) {
$details[$x]['budget_id'] = $id;
$details[$x]['office'] = $offices[$x];
$details[$x]['vote_id'] = $votes[$x];
$details[$x]['amount'] = (-1)*$amount[$x];
$details[$x]['notes'] = $notes[$x];
$details[$x]['budget_date'] = $bdate[$x];
$details[$x]['status'] = 1;
}
Now the issue was fixed partially. But the saving vote_id of finance_budget_issue table is incorrect without editing.

second page is not updating while using tr dir-paginate

I am using onaftersave() function to save the table data. In dir-paginate i am using ng-repeat to read the table row values. I kept itemsperpage is 5. obviously 6th row will be display in second Page. When I try to edit the second page row values it is not updating the second page rows. How to resolve it?
<form editable-form name="tableform1" oncancel="cancel()" onaftersave="saveTable(Manage_Role.Description)">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default panel-table">
<div class="panel-heading">
<div class="row">
<div class="col col-xs-6">
</div>
<div class="col col-xs-6 text-right">
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-sm btn-primary btn-create" title="Add New Role">Add New Role</button>
</div>
</div>
</div>
<div class="panel-body scrollbar">
<table class="table table-striped table-bordered table-list">
<thead>
<tr>
<th style="width: 25%" align="center">
Name
</th>
<th style="width: 35%">
Description
</th>
<th style="width: 30% " align="center">
IsActive?
</th>
<th style="width: 10% " align="center"><a href="" ng-click="orderByField='IsActive';
reverseSort = !reverseSort" title="Assign">Assign</a></th>
<th style="width: 1%" align="center" ng-show="false">DirtyFlag</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" id="RoleNameID" ng-model="Manage_Role1.RoleName" placeholder="search" class="searchbox" onkeydown="return (event.keyCode!=13);"
/>
</td>
<td>
<input type="text" id="DescriptionID" ng-model="Manage_Role1.Description" placeholder="search" class="searchbox" onkeydown="return (event.keyCode!=13);"
/>
</td>
<td>
<select name="DropFilter" ng-model="Manage_Role1.IsActive" class="searchbox">
<option value="">All</option>
<option value=false>False</option>
<option value=true>True</option>
</select>
</td>
<!--<td></td>-->
</tr>
<tr dir-paginate="Manage_Role in Manage_Roleser | itemsPerPage:5 | filter:DropFilter | filter:Manage_Role1 | orderBy:orderByField:reverseSort "
ng-class-odd="'odd'">
<td ng-click="tableform1.$show()">
<span e-ng-change="applyHighlight($data,$index)" editable-text="Manage_Role.RoleName" ng-attr-title="{{Manage_Role.RoleName}}"
e-form="rowform" ng-click="rowform.$show()">
{{ Manage_Role.RoleName | uppercase }}
</span>
</td>
<td ng-click="tableform1.$show()">
<div>
<span e-ng-change="applyHighlight($data,$index)" editable-text="Manage_Role.Description" e-form="rowform" ng-attr-title="{{Manage_Role.Description}}"
ng-click="rowform.$show()">
{{ Manage_Role.Description || 'empty' }}
</span>
</div>
</td>
<td ng-click="tableform1.$show()" align="center">
<span e-ng-change="applyHighlight($data,$index)" ng-checked="Manage_Role.IsActive" editable-checkbox="Manage_Role.IsActive"
e-form="rowform" ng-click="applyHighlight($data,$index);tableform.$show()">
<input type="checkbox" ng-model="Manage_Role.IsActive" width="20" ng-attr-title="{{Manage_Role.IsActive}}" />
</span>
</td>
<td align="center">
<input type="image" data-toggle="modal" ng-click="Rolepopupclick(Manage_Role._id,Manage_Role.RoleName)" title="Assign UI"
data-target="#Div1" src="App_Themes/Images/AssignUser.png"
alt="Submit" width="28" height="28" />
</td>
<td ng-show="false">
<input type="text" ng-model="Manage_Role.DirtyFlag" ng-show="false" />
</td>
</tr>
</tbody>
</div>
</table>
</div>
<div class="panel-footer">
<div class="row">
<div class="col col-xs-8">
<dir-pagination-controls max-size="5" direction-links="true" boundary-links="true">
</dir-pagination-controls>
</div>
<div class="col col-xs-4">
<div class="btn-form" ng-show="tableform1.$visible" style="float:right">
<button type="submit" ng-disabled="tableform1.$waiting" title=" Save Changes" class="btn btn-primary fa fa-save" ng-click="NotifyClick()"> Save</button>
<input type="button" ng-disabled="tableform1.$waiting" title=" Close Edit Form Without Saving Changes" ng-click="refreshUI();tableform1.$cancel()"
class="btn btn-danger fa fa-close" value="X Cancel" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
controller code:
$scope.saveTable = function ()
{
debugger;
if(NotifyCount!=1){
var RoleNamechk = '';
for (var i = 0; i < $scope.Manage_Roleser.length; i++) {
RoleNamechk = $scope.Manage_Roleser[i].RoleName;
for (var j = 0; j < $scope.Manage_Roleser.length; j++) {
var RoleName = $scope.Manage_Roleser[j].RoleName;
if (RoleNamechk == RoleName) {
count++;
}
}
}
if (count == $scope.Manage_Roleser.length)
{
for (var i = 0; i < $scope.Manage_Roleser.length; i++) {
var id = $scope.Manage_Roleser[i]._id;
var rolename = $scope.Manage_Roleser[i].RoleName;
var isactive = $scope.Manage_Roleser[i].IsActive;
var description = $scope.Manage_Roleser[i].Description;
if (description == "")
{
description = 'empty';
}
if ($scope.Manage_Roleser[i].DirtyFlag == "True")
{
$scope.LoggedinUsers = $cookieStore.get('LoggedinUser');
var updatedBy= $scope.LoggedinUsers;
$http.put('/Roleupdate/' + id + '/' + rolename + '/' + isactive + '/' + description + '/' + updatedBy).then(function (response) {
refresh();
});
}
count=0;
}
$notify.success('Success', 'Role is Updated Successfully');
}
else {
$notify.warning('Warning', 'Role Name is Already Exists');
count = 0;
return '';
}
}
};
in ng-change I am checking dirty flag of selected index because it is updating all the row values. for that I am updating only selected($dirty) row alone. In second page it is not taking table index correctly. If I select 2nd page 3 row it will assume or taking index of the particular page. It should take index of selected row from the over all table row
$scope.applyHighlight = function ($data,index) {
$scope.Manage_Roleser[index].DirtyFlag = "True";
var dataSpan = $(event.currentTarget).closest('td');
if (!dataSpan.hasClass("highlighted")) {
$(dataSpan).addClass("highlighted");
}
}

Displaying data from database from Controller to View using jQuery AJAX request CodeIgniter without refreshing the page

How i can load particular portion of page in Codeigniter? The Ajax is working but it reloads all views by calling controller name(like header, body, footer) but i want only reload body, How can i separate the code to work properly.
Its Ajax code
$('label#showdata').click(function(){
var fromdate =document.getElementById('fromdate').value;
var todate = $(this).val();
var dataString = 'fromdate='+ fromdate+'todate='+todate;
$.ajax({
type: "POST",
url: "https://chotigaadi.com/myadmin/references",
data: dataString,
cache: false,
success: function(html)
{
$("div#result").html(html).show();
//alert(dataString);
}
});
});
Its my View
<div class="col s12 m12">
<form action="<?php echo base_url();?>myadmin/ExportCSV" method="POST">
<div class="col s12 m3">
<h5 class="center" style="color:green;font-weight:bold;">Registered Members List</h5>
</div>
<div class="col s12 m2">
<div class="input-field col s12">
<label for="date"> <i class="fa fa-calendar"></i> Select from date below:</label>
</br>
<input name="fromdate" id="fromdate" type="date" class="datepicker" required>
</div>
</div>
<div class="col s12 m3">
<div class="input-field col s12">
<label for="date"> <i class="fa fa-calendar"></i> Select to date below:</label>
</br>
<input name="todate" id="todate" type="date" class="datepicker" required>
</div>
</div>
<div class="col s12 m4">
<div class="col s6">
<label id="showdata" class="btn waves-effect waves-light orange right" value="Show">Show Results</label>
</div>
<div class="col s6">
<input type="submit" id="datesubmit" class="btn waves-effect waves-light green right" value="Export Data" />
</div>
</div>
</form>
<div id="result">
<table class="highlight">
<thead>
<tr style="background-color:#ccc;">
<th data-field="name">ID</th>
<th data-field="name">Referee</th>
<th data-field="rname">Reference</th>
<th data-field="email">Email</th>
<th data-field="phone">Phone</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $row)
{?>
<tr style="">
<td>
<?php echo $row->firstname;?>
</td>
<td>
<?php echo $row->name; ?>
</td>
<td>
<?php echo $row->email; ?>
</td>
<td>
<?php echo $row->phone; ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
My Controller Code:
function references(){
if (!$this->check_user()) {
redirect('myadmin/login/');
}
else
{
if(isset($_POST['fromdate']) && isset($_POST['todate']))
{
$fromdate=new DateTime(str_replace("-","",$_POST['fromdate']));
$fromdate=$fromdate->format('Y-m-d H:i:s');
$todate=new DateTime(str_replace("-","",$_POST['todate']));
$todate=$todate->format('Y-m-d H:i:s');
}
else
{
$fromdate=new DateTime('2015-12-10 14:28:27');
$fromdate=$fromdate->format('Y-m-d H:i:s');
$todate=new DateTime(date("Y-m-d"));
$todate=$todate->format('Y-m-d H:i:s');
}
$config = array();
$config["base_url"] = base_url() . "myadmin/references";
$config["total_rows"] = $this->myadmin_model->record_count($fromdate, $todate);
$config["per_page"] = 8;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->myadmin_model->fetch_userdata($config["per_page"], $page, $fromdate, $todate);
$data["links"] = $this->pagination->create_links();
$this->load->view('/admin/myadminheader');
$this->load->view('/admin/myadmin',$data);
$this->load->view('/admin/myadminfooter');
}
}
I want to reload only view as $this->load->view('/admin/myadmin',$data); by ajax How I can do this?
If you just want to change your middle part only than do not load header and footer in ajax calling function.
Remove these two lines:
$this->load->view('/admin/myadminheader');
$this->load->view('/admin/myadminfooter');
It just only:
$this->load->view('/admin/myadmin',$data);
This will only return the middle part not header footer in ajax response.
Side note:
If you are using this function directly from some where than you need to pass any param from ajax request for checking either request from ajax or not.
Don't load the view in controller function. Just print the result in controller function and write a die() function after that. Clear the result div in JavaScript function before load the html.