datewise searching not working in pagination - codeigniter

My search result correctly displaying. But when I click the second page or pagination then all the data is displaying
my view - date selecting
Here I select the date using the date picker
<div class='floatl modal-form col-sm-12'>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableFrom'
placeholder='date from'/>
</div>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableTo'
placeholder='date to'/>
</div>
<div class='col-sm-2'>
<button class='btn-success' onclick="filterTable()"> Filter</button>
</div>
</div>
<div class='contentTable'>
<?php
$this->load->view("pages/tableData/leads_data");
?>
</div>
<script>
$(function () {
$(".dateTablePicker").datepicker({dateFormat: 'yy-mm-dd'});
});
function filterTable() {
$.ajax({
type: "POST",
url: "<?= site_url('OperationRouter/filterTableData'); ?>",
data: {dateTableFrom: $('#dateTableFrom').val(), dateTableTo: $('#dateTableTo').val()},
success: function (data) {
$(".contentTable").html(data);
}
});
}
leads_data//table data listing
The data displaying if the datefrom and dateto is isset then data displaying based on searching.
<?php
if (!isset($_SESSION['dateTableFrom'])) $_SESSION['dateTableFrom'] = '';
if (!isset($_SESSION['dateTableTo'])) $_SESSION['dateTableTo'] = '';
$dateTableFrom = $_SESSION['dateTableFrom'];
$dateTableTo = $_SESSION['dateTableTo'];
$page='leads';
$slno = 0;
// CONDITION QUERY
if (isset($_SESSION['export_Sql']))
$cql = $_SESSION['export_Sql'];
else if($dateTableFrom) {
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
and STR_TO_DATE(leads.created,"%d-%m-%Y") >= "' . $dateTableFrom . '"
and
STR_TO_DATE(leads.created,"%d-%m-%Y") <= "' . $dateTableTo . '"
';
}
else
{
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
';
}
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) {
$cql .= " and leads.id in (" . $_SESSION['export_Ids'] . ") ";
}
if (isset($_SESSION['export_Order']) &&
$_SESSION['export_Order'])
$oql = $_SESSION['export_Order'];
else
$oql = ''; // ORDER QUERY
if (isset($_SESSION['export_Limit']))
$lql = $_SESSION['export_Limit'];
else
$lql='';
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) // IF ID'S
THEN NO EXPORT LIMIT NEEDED
$lql = '';
$sql = $cql . $oql;
$itemcount = $this->OperationModel->getRowCount($sql);
$sql = $cql . $oql . $lql;
?>
<input type='hidden' id='selectedSql' value='<?= $cql ?>'/>
<input type='hidden' id='selectedOrder' value='<?= $oql ?>'/>
<input type='hidden' id='selectedLimit' value='<?= $lql ?>'/>
<?php
$slno = 0;
//$sql='select * from admin_types where remove_status = 1';
$tableArray['searchFields'] = 'leads.title';
$itemsperpage = 6;
$result = $this->OperationModel->getTableData($sql,
$tableArray['searchFields'], $itemsperpage);
if (isset($result['data'])) {
$admin_det = $this->Adminuser->getsingleadmin($this->session-
>userdata['logged_admin']);
?>
<div class='custom-data-table '>
<table class='customtable'>
<tr>
<th style='width:70px;' class='checker'>
<input type='checkbox' class='thCheckbox'/>
<div class='customCheckbox'></div>
</th>
<th style='width:60px;'> No</th>
<th style='width:230px;'>
Title
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.title'
title='sort records by title'></i>
</div>
</th>
<th>
Date
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.created'
title='sort records by date '></i>
</div>
</th>
<th>
Service
<div class='floatr'><i class='i-sorter icon-shuffle'
data='products.title'
title='sort records by date '></i>
</div>
</th>
<th>
Client
<div class='floatr'><i class='i-sorter icon-shuffle'
data='companies.title'
title='sort records by company'>
</i></div>
</th>
<th>
Owner
<div class='floatr'><i class='i-sorter icon-shuffle'
data='admin.username'
title='sort records by owner'></i></div>
</th>
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<th> Conversion
<div class='floatr'><i class='i-sorter icon-
shuffle' data='leads.converted_flag'
title='sort records by
conversion status'></i></div>
</th>
<?php } ?>
<!--
<th>
Status
</th>
!-->
<th> Actions</th>
<?php } ?>
</tr>
<?php
// $slno=intval($current_page);
if (isset($searchkey)) $searchkey = $searchkey; else $searchkey
= '**';
foreach ($result['data'] as $row) {
$slno++;
?>
<tr id='<?= $row['id'] ?>'>
<td>
<input type='checkbox' class='tdCheckbox'/>
<div id='<?= $row['id'] ?>' class='customCheckbox'>
</div>
</td>
<td> <?= $slno ?> </td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['title'], $searchkey) ?></td>
<td><?= $row['created'] ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['product'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['company'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['username'], $searchkey) ?></td>
<!--
<td><?= $row['lead_status'] ? '<span
style="color:green">Active</span>' : '<span
style="color:orange">Inactive</span>' ?></td>
!-->
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<td>
<button class='status-button'
data-trigger='leads'
data-value='<?=
$row['converted_flag'] ?>'
data-raw='<?= $row['id'] ?>'
data-field='converted_flag'
data-success="<span
class='colorange'>DisConvert</span>"
data-failure="<span
class='colgreen'>Convert</span>">
<?= ($row['converted_flag'] == 1) ? "
<span class='colorange'>DisConvert</span>" : "<span
class='colgreen'>Convert</span>" ?>
</button>
</td>
<?php } ?>
<td>
<?php
if ($row['creator_id'] ==
$_SESSION['logged_admin'] || $admin_det[0]['user_type'] ==
'admin' || $admin_det[0]['user_type'] == 2) { ?>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createmeeting'>
<i class='fa fa-plus add-bt'></i>
Meeting
</a>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-pencil ed-bt'></i>
</a>
<?php if ($admin_det[0]['user_type'] ==
'admin') { ?>
<a class='delete-trigger' data-
trigger='leads' data-raw='<?= $row['id'] ?>'>
<i class='fa fa-trash del-bt'></i>
</a>
<?php } ?>
<?php } ?>
<a class='modal-switch'
data-toggle='modal'
data-operation='view'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-eye ed-bt'></i>
</a>
</td>
<?php } ?>
</tr>
<?php
}
?>
</table>
</div>
<?php
/* THE PAGINATION PART */
$pagination['base_url'] = $page;
$pagination['itemsperpage'] = $itemsperpage;
$pagination['total_rows'] = $this->OperationModel->getRowCount($sql,
$tableArray['searchFields']);
/* THE PAGINATION PART */
if (isset($pagination))
echo $this->OperationModel->getPagination($pagination);
?>
<?php
} else {
echo " <span class='floatl no-match-span'> <i class='icon-magnifier'></i>
<span>Oopz , No data found in database for the corresponding item .
</span> </span> ";
}
?>
<?php
$this->session->unset_userdata('dateTableFrom');
?>
pagination part
Here is the pagination part
function getPagination($dataArray = '')
{
$msg = '';
if ($dataArray) {
$this->load->library('pagination');
$config['base_url'] = base_url() . $dataArray['base_url'];
//$config['base_url'] = base_url('controller_name/search');
$config['uri_segment'] = 2;
$config['total_rows'] = $dataArray['total_rows'];
$config['per_page'] = $dataArray['itemsperpage'];
$this->pagination->initialize($config);
$msg .= "<div class='pagination'>";
$msg .= $this->pagination->create_links();
$msg .= "</div>";
return $msg;
} else
return false;
}

You should pass the search params (filters) along with the ajax request. (along with the pagination)

Related

Pagination with Search Filter in CodeIgniter

When I search a keyword and paginate it, it returns data that matches the like query in the database.
A PHP Error was encountered
Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: admin/view_member.php
Line Number: 105
Backtrace:
File: C:\xampp\htdocs\cms_new\application\views\admin\view_member.php
Line: 105
Function: _error_handler
File: C:\xampp\htdocs\cms_new\application\controllers\admin\Member.php
Line: 63
Function: view
File: C:\xampp\htdocs\cms_new\index.php
Line: 315
Function: require_once
MY Controller
$search = ($this->input->post("member_name"))? $this->input->post("member_name") : "NIL";
$search = ($this->uri->segment(3)) ? $this->uri->segment(3) : $search;
// pagination settings
$config = array();
$config['base_url'] = site_url("admin/member/index/$search");
$config['total_rows'] = $this->Model_member->record_count($search);
$config['per_page'] = "3";
$config["uri_segment"] = 4;
$choice = $config["total_rows"]/$config["per_page"];
$config["num_links"] = floor($choice);
// integrate bootstrap pagination
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
$config['first_link'] = false;
$config['last_link'] = false;
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['prev_link'] = 'Prev';
$config['prev_tag_open'] = '<li class="prev">';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['page'] = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
// get books list
$data['users'] = $this->Model_member->fetch_data($config['per_page'], $data['page'], $search);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('admin/view_header',$data);
$this->load->view('admin/view_member',$data);
$this->load->view('admin/view_footer');
My Model
function fetch_data($limit, $start, $st = NULL)
{
if($st == "NIL")
$st = "";
$this->db->select('*');
$this->db->from('tbl_member');
$this->db->like('member_name', $st);
$this->db->or_like('member_email', $st);
$this->db->limit($limit, $start);
$query = $this->db->get();
if ($query->num_rows() > 0) {
//var_dump($query->result());
foreach ($query->result() as $row) {
$data[] = $row;
}
//print_r($query);
return $data;
}
if ($query->num_rows() == 0) {
$this->session->set_flashdata('recoard','<div class="alert alert-danger text-center">Record Not Found! </div>');
}
return false;
}
function record_count($st = NULL)
{
if($st == "NIL")
$st = "";
$this->db->select('*');
$this->db->from('tbl_member');
$this->db->like('member_name', $st);
$this->db->or_like('member_email', $st);
$query = $this->db->get();
return $query->num_rows();
var_dump($query->num_rows());
}
My View
<?php
$user = count($users);
var_dump($user);
for ($i = 0; $i < $user; ++$i) {
if(! $users ){
// Faild Message
echo $this->session->flashdata('recoard');
}
else {
?>
<tbody>
<tr>
<td class="text-center"><img class="rounded-circle img-fluid avatar-40" src="<?php echo base_url();; ?>public/uploads/<?php echo $users[$i]->member_photo; ?>" alt="profile"></td>
<td><?php echo $users[$i]->member_name; ?></td>
<td><?php echo $users[$i]->member_email; ?><br>
<?php echo $users[$i]->member_mobile; ?></td>
<td><?php echo $users[$i]->member_city; ?><br>
<?php echo $users[$i]->member_state; ?><br>
<?php echo $users[$i]->member_country; ?></td>
<td><?php echo $users[$i]->member_address; ?></td>
<td>
<?php
if($users[$i]->member_access == 1)
{
echo '<span class="badge iq-bg-primary">Active</span></td>';
}
else
{
echo '<span class="badge iq-bg-warning">Inactive</span></td>';
}
?>
</td>
<td>
<div class="flex align-items-center list-user-action">
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Change Status" href="<?php echo base_url(); ?>admin/member/change_status/<?php echo $users[$i]->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="ri-user-add-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" href="<?php echo base_url(); ?>admin/member/edit/<?php echo $users[$i]->member_id; ?>"><i class="ri-pencil-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" href="<?php echo base_url(); ?>admin/member/delete/<?php $users[$i]->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="iq-bg-danger ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
</tbody>
<?php } } ?>
you seem to not be returning an array to count & loop over, this is why you have the warning.
Also you have the failed message inside your loop that will make more errors later on.
Hope this helps & works for you
<?php
if (!$users || !is_array($users)) {
// Faild Message
echo $this->session->flashdata('recoard');
} else {
foreach ($users as $user) { ?>
<tbody>
<tr>
<td class="text-center"><img class="rounded-circle img-fluid avatar-40" src="<?php echo base_url("public/uploads/"); ?><?php echo $user->member_photo; ?>" alt="profile"></td>
<td><?php echo $user->member_name; ?></td>
<td><?php echo $user->member_email; ?><br>
<?php echo $user->member_mobile; ?></td>
<td><?php echo $user->member_city; ?><br>
<?php echo $user->member_state; ?><br>
<?php echo $user->member_country; ?></td>
<td><?php echo $user->member_address; ?></td>
<td>
<?php
if ($user->member_access == 1) {
echo '<span class="badge iq-bg-primary">Active</span></td>';
} else {
echo '<span class="badge iq-bg-warning">Inactive</span></td>';
}
?>
</td>
<td>
<div class="flex align-items-center list-user-action">
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Change Status" href="<?php echo base_url(); ?>admin/member/change_status/<?php echo $user->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="ri-user-add-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" href="<?php echo base_url(); ?>admin/member/edit/<?php echo $user->member_id; ?>"><i class="ri-pencil-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" href="<?php echo base_url(); ?>admin/member/delete/<?php $user->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="iq-bg-danger ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
</tbody>
<?php }
} ?>

How to accept or reject the data using checkbox in codeiginter?

I am accepting and rejecting some data while clicking checkbox.From my code accept code is working well but rejected is same type of code but it is not working well.
My view page code:
<form class="form-horizontal" method="POST" action="<?=site_url('Request/Update_Event')?>">
<div class="panel panel-flat" id="id">
<div class="panel-heading">
<center> <h4 class="panel-title">Request Portal</h4></center>
</div> <button type="submit" class="btn btn-info btn-lg">
<span class="glyphicon glyphicon-thumbs-up"></span>Approved
</button> <a href="<?=site_url('Request/Rejected')?>" class="btn btn-info btn-lg" id="but">
<span class="glyphicon glyphicon-thumbs-down"></span> Rejected
</a><div>
My Controller Code:
public function Update_Event(){
$empid = $this->input->post('empid');
for($i=0; $i< sizeof($empid); $i++)
{
$data = array(
'backgroundColor' => 'green',
'event_status' =>'Approved',
);
$this->db->where(empid,$empid[$i]);
$this->db->update('events',$data);
}
redirect('Request','refresh');
}
public function Rejected(){
$empid = $this->input->post('empid');
for($i=0; $i< sizeof($empid); $i++)
{
$data = array(
'backgroundColor' => 'red',
'event_status' =>'Rejected',
);
$this->db->where(empid,$empid[$i]);
$this->db->update('events',$data);
}
redirect('Request','refresh');
print_r($empid);
}
My table code:
<table id="tb2" class="table datatable-responsive" >
<thead><tr><h6><th></th><th align="center">Name</th>
<th class="col-sm" >Leave Date</th>
<th class="col-sm" >Reason</th>
</tr></thead>
<?php foreach ($query as $row): ?>
<tr><td><input type="checkbox" name="empid[]" value="<?php echo $row['empid'];?>"></td>
<td>Leave Applied By <?php echo $row['first_name'];?> <?php echo $row['last_name'];?></td>
<td><?php echo date('d/m/Y', strtotime($row['event_date']));?></td>
<td><?php echo $row['title'];?> </td>
</tr></tbody><?php endforeach ?>
</table>
The rejected code is not working in my code and the empid is not passed to Rejected code when i print the empid value
You are facing this issue because at approval time you are submitting form and in rejection time you are only clicking on link. So when you click on reject button it will not post any value to controller.
You can do something like this. just pass extra parameter to reject function.
<a href="<?=site_url('Request/Rejected/123')?>" class="btn btn-info btn-lg" id="but">
<span class="glyphicon glyphicon-thumbs-down"></span> Rejected
</a>
public function Rejected($empid = ''){
for($i=0; $i< sizeof($empid); $i++)
{
$data = array(
'backgroundColor' => 'red',
'event_status' =>'Rejected',
);
$this->db->where(empid,$empid[$i]);
$this->db->update('events',$data);
}
redirect('Request','refresh');
print_r($empid);
}

Multidimensional input with codeigniter not setting second array correct

On my controller function get form I get my banner images and I also use multidimensional array in my view
For some reason, the second banner_image title not showing but the value has been placed on the first array instead?
print_r($_POST)
Question How am I able to make sure that no matter how many banner images I select it can set the multidimensional array correct for each post.
public function getForm()
{
$banner_id = $this->uri->segment(5);
if ($banner_id)
{
$data['action'] = 'admin/design/banners/edit/' . $banner_id;
} else {
$data['action'] = 'admin/design/banners/add';
}
$banner_info = $this->admin_model_banner->getBanner($banner_id);
if ($this->input->post('banner_name')) {
$data['banner_name'] = $this->input->post('banner_name');
} elseif (!empty($banner_info)) {
$data['banner_name'] = $banner_info['banner_name'];
} else {
$data['banner_name'] = '';
}
if ($this->input->post('banner_status')) {
$data['banner_status'] = $this->input->post('banner_status');
} elseif (!empty($banner_info)) {
$data['banner_status'] = $banner_info['status'];
} else {
$data['banner_status'] = '';
}
$banner_images = array();
$banner_images_post = $this->input->post('banner_image');
if (isset($banner_images_post)) {
$banner_images = $this->input->post('banner_image');
} elseif (isset($banner_id)) {
$banner_images = $this->admin_model_banner->getBannerImages($banner_id);
}
$data['banner_images'] = array();
foreach ($banner_images as $banner_image)
{
if (is_file(FCPATH . 'image/' . $banner_image['image'])) {
$image = $banner_image['image'];
$thumb = $banner_image['image'];
} else {
$image = '';
$thumb = 'catalog/no_image.jpg';
}
$data['banner_images'][] = array(
'image' => $image,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'title' => $banner_image['title'],
'sort_order' => $banner_image['sort_order']
);
}
$data['placeholder'] = $this->model_tool_image->resize('catalog/no_image.jpg', 100, 100);
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('design/banner_form_view', $data);
}
View
<?php echo $header;?>
<div class="container">
<?php
$form = array(
'id' => '',
'role' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart($action, $form);?>
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Banner Status</label>
<div class="col-lg-10">
<input type="text" name="banner_name" class="form-control" placeholder="Enter Banner Name" value="<?php echo $banner_name;?>" size="50"/>
<?php echo form_error('banner_name', '<div class="text-danger" style="margin-top: 2rem;">', '</div>'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Banner Name</label>
<div class="col-lg-10">
<?php
$options = array('1' => 'Enabled', '0' => 'Disabled');
echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));
?>
</div>
</div>
<table id="images" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left">Title</td>
<td class="text-left">Image</td>
<td>Sort Order</td>
</tr>
</thead>
<tbody>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td class="text-left">
<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" value="<?php echo $banner_image['title']; ?>" class="form-control">
</td>
<td class="text-left">
<a href="" id="thumb_image_<?php echo $image_row; ?>" data-toggle="image" class="img-thumbnail">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" />
</a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input_image_<?php echo $image_row; ?>" /></td>
<td class="text-right"><input type="text" name="banner_image[<?php echo $image_row; ?>][sort_order]" value="<?php echo $banner_image['sort_order']; ?>" placeholder="Sort Order" class="form-control" /></td>
<td class="text-left">
<button type="button" onclick="$('#image-row<?php echo $image_row; ?>').remove();" class="btn btn-danger"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td colspan="3"></td>
<td class="text-left">
<button type="button" onclick="addImage();" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
</tfoot>
</table>
</div>
<div class="panel-footer">
<div class="text-right"><button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</button></div>
</div>
</div>
<?php echo form_close();?>
</div>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage()
{
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" class="form-control" value="">';
html += '</td>';
html += '<td class="text-left">';
html += '<a href="" id="thumb_image_' + image_row + '" data-toggle="image" class="img-thumbnail">';
html += '<img src="<?php echo $placeholder; ?>" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '</a>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input_image_' + image_row + '" />';
html += '</td>';
html += '<td class="text-right">';
html += '<input type="text" name="banner_image[' + image_row + '][sort_order]" value="" placeholder="Sort Order" class="form-control" />';
html += '</td>';
html += '</tr>';
$('#images tbody').append(html);
image_row++;
}
</script>
Solved
After doing some investigation I found problem was to do with
name="banner_image[<?php echo $image_row; ?>][title]"
On script, I forgot to add it like
name="banner_image[' + image_row + '][title]"
Working now

shopping cart in codeigniter using ajax

Hi I am new with ajax and having problem. I am trying to make a shopping cart using ajax.I don't know what is wrong with my code please help me out.
When I click the add button an alert comes 'No success' and nothing happen , I am not able add items to cart.
Thanks for helping me.
This is my view
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $(this).serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping2/add",
dataType: 'json',
//type: "POST",
data: insert_data,
success:function(response) {
//if (response){
//var res = JSON.parse(response);
var res = response;
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping2";
}else{
alert(res.msg);
}
//}
//else{
// alert('sorry');
//}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<div id="addcart">
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping2/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well" id="addcart">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping2/remove'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr></div>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
</html>
This is my controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping2 extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_view2', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
//$success = $this->cart->insert($insert_data);
$cart_check = $this->cart->contents();
if(!empty($cart_check)){
//$this->cart->contents(insert_data);
$res = array('status' => 200, 'msg' => 'success');
}else{
$res = array('status' => 500, 'msg' => 'No success');
}
echo json_encode($res);
//echo $data[0]['value'];
//redirect('shopping2');
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
$this->cart->destroy();
}else{
$data = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($data);
}
redirect('shopping2');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping2');
}
}
Please help me how to add items in the cart using ajax.
Since u managed to get a response, the problem should lie in your Model or data insertion.
Few suggestions:
It's also recommended that you use $.post() instead of $.ajax().
"<?php echo base_url(); ?>" + "index.php/shopping2/add" can be changed to "<?php echo site_url('shopping2/add"'); ?>"
Use the built in Codeignter output class to output your JSON. See here: https://www.codeigniter.com/userguide3/libraries/output.html

What Script, Ajax , Controller codes are responsible for saving quantity

Below code we are using to display quantity text field and update quantity.
I want to know what all code is there in behind to update this quantity.
Means what script, ajax, contoller codes are responsible for saving this quantity.
<li class="fields">
<div class="customer-name">
<div class="field">
<label class="required" for="qty"><em>*</em><?php echo $helper->__('Quantity')?></label>
<div class="input-box">
<input type="text" name="qty" id="qty" value="<?php echo intval($mpAssignProductModel->getQty()) ?>" class="required-entry validate-zero-or-greater input-text"/>
</div>
</div>
</div>
</li>
because when i used above code in another file. It didt worked for me.
another page was displaying like this before :
After i replaced above code in another phtml file, its displaying like this :
This is complete code of file where updating quantity is not working :
phtml code :
<?php
$helper=Mage::helper('mpassignproduct');
$isPartner= Mage::getModel('marketplace/userprofile')->isPartner();
if($isPartner==1){ ?>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
document.write(unescape("%3Cscript src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<div>
<div class="page-title">
<h1><?php echo $helper->__('My Assign Product List') ?></h1>
</div>
<div class="wk_mp_design">
<div class="block block-account">
<div class="block-title">
<strong><span><h4><?php echo $helper->__('My Assign Product List'); ?></h4></span></strong>
</div>
</div>
<div class="fieldset wk_mp_fieldset">
<div class="grid">
<div class="hor-scroll">
<?php
if(count($this->getCollection())==0): ?>
<div class="fieldset wk_mp_fieldset">
<div class="wk_emptymsg">
<?php echo $helper->__('No Product Available') ?>
</div>
</div>
<?php else: ?>
<form action="<?php echo Mage::helper('core/url')->getCurrentUrl();?>" method="post">
<table cellspacing="0" class="border wk_mp_list_table">
<thead>
<tr id="wk_mp_tr_heading">
<th><span><?php echo $helper->__('Product Name') ?></span></th>
<th><span><?php echo $helper->__('Date') ?></span></th>
<th><span><?php echo $helper->__('Product Status') ?></span></th>
<th><span> </span></th>
</tr>
</thead>
<tbody class="wk_mp_body">
<tr>
<td>
<input type="text" class="input-text" name="s" placeholder='<?php echo $helper->__('Search by product name') ?>' value="<?php echo $this->getRequest()->getParam('s')?>"/>
</td>
<td>
<span class="wk_mp_td_span">
<?php echo $helper->__('From: ') ?>
<input name="from_date" id="special_from_date" class="input-text" value="<?php echo $this->getRequest()->getParam('from_date')?>" />
</span>
<span class="wk_mp_td_span">
<?php echo $helper->__('To: ') ?>
<input name="to_date" id="special_to_date" class="input-text" value="<?php echo $this->getRequest()->getParam('to_date')?>" />
</span>
</td>
<td>
<select name="prostatus" class="input-text">
<option value=""><?php echo $helper->__('All') ?></option>
<option value="1" <?php if($this->getRequest()->getParam('prostatus') == 1) echo 'selected="selected"'?>>
<?php echo $helper->__('Approved') ?>
</option>
<option value="2" <?php if($this->getRequest()->getParam('prostatus') == 2) echo 'selected="selected"'?>>
<?php echo $helper->__('Unapproved') ?>
</option>
</select>
</td>
<td>
<button class="button" title="Save" type="submit">
<span><span><span><?php echo $helper->__('Submit') ?></span></span></span>
</button>
</td>
</tr>
</tbody>
</table>
</form>
<form name="formmassdelete" id="form-customer-product-delete" method="post" action="<?php echo $this->getUrl('mpassignproduct/index/massdeletepro') ?>">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
<button id="mass_delete_butn" style="float: left;padding: 5px 5px 5px 0;" type="submit" title="Delete Sellers" class="button">
<span><span>Delete Products</span></span>
</button>
<table cellspacing="0" class="border wk_mp_list_table wk_mp_list_container_table">
<thead>
<tr class="wk_content">
<th class="wk_check_first_td">
<span><input type="checkbox" id="mpselecctall" value="all" name="mpselecctall"></span>
</th>
<th class="wk_first_td">
<span class="label "><?php echo $helper->__('Product Name')?></span>
</th>
<th>
<span class="label name"><?php echo $helper->__('Price')?></span>
</th>
<th>
<span class="label name"><?php echo $helper->__('SKU')?></span>
</th>
<th>
<span class="label name"><?php echo $helper->__('Delivery Time')?></span>
</th>
<th>
<span class="label name"><?php echo $helper->__('Replacement Guarantee')?></span>
</th>
<th>
<span class="label qty"><?php echo $helper->__('Status')?></span>
</th>
<th>
<span class="label qty"><?php echo $helper->__('Qty.')?></span>
</th>
<th>
<span class="label qty"><?php echo $helper->__('Condition')?></span>
</th>
<th>
<span class="label"><?php echo $helper->__('Action')?></span>
</th>
</tr>
</thead>
<tbody>
<?php foreach($this->getCollection() as $assinproducts): ?>
<?php $products=Mage::getModel('catalog/product')->load($assinproducts->getProductId()); ?>
<tr class="wk_row_view ">
<td class="wk_check_first_td">
<span>
<input type="checkbox" value="<?php echo $assinproducts->getMpassignproductId(); ?>" class="mpcheckbox" name="product_mass_delete[]">
</span>
</td>
<td class="wk_first_td">
<span class="label name" title="<?php echo $products->getName(); ?>">
<?php
$productname=strlen($products->getName())>7?substr($products->getName(),0,7)."..":$products->getName();
echo $products->getName();
?>
</span>
</td>
<td>
<span class="label price">
<?php echo Mage::helper('core')->currency($assinproducts->getPrice(), true, false);?>
</span>
</td>
<td>
<span class="label sku">
<?php echo $assinproducts->getsku() ?>
</span>
</td>
<td>
<span class="label replacement">
<?php echo $assinproducts->getdeliverytime() ?>
</span>
</td>
<td>
<span class="label delivery">
<?php echo $assinproducts->getreplacement() ?>
</span>
</td>
<td>
<span class="label pro_status">
<?php if($assinproducts['flag']==1): ?>
<?php echo Mage::helper('mpassignproduct')->__('Approved')?>
<?php else: ?>
<?php echo Mage::helper('mpassignproduct')->__('Un-Approved')?>
<?php endif; ?>
</span>
</td>
<td>
<li class="fields">
<div class="customer-name">
<div class="field">
<label class="required" for="qty"><em>*</em><?php echo $helper->__('Quantity')?></label>
<div class="input-box">
<input type="text" name="qty" id="qty" value="<?php echo intval($mpAssignProductModel->getQty()) ?>" class="required-entry validate-zero-or-greater input-text"/>
</div>
</div>
</div>
</li>
</td>
<td>
<span class="label">
<?php
if($assinproducts['product_condition']=='new')
echo Mage::helper('mpassignproduct')->__('New');
else
echo Mage::helper('mpassignproduct')->__('Used');
?>
</span>
</td>
<td>
<span class="label wk_action">
<img src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?>" data-type="<?php echo $assinproducts->getMpassignproductId(); ?>" alt="<?php echo $helper->__('Edit')?>" title="<?php echo $helper->__('Edit')?>" class="mp_edit"/>
<img data-type="<?php echo $assinproducts->getMpassignproductId(); ?>" src="<?php echo $this->getSkinUrl('marketplace/images/icon-trash.png'); ?>" alt="<?php echo $helper->__('Delete')?>" title="<?php echo $helper->__('Delete')?>" class="mp_delete"/>
</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
<?php endif; ?>
</div>
</div>
<?php echo $this->getPagerHtml(); ?>
</div>
</div>
<div class="buttons-set">
<p class="back-link">
« <?php echo Mage::helper('marketplace')->__('Back') ?>
</p>
</div>
</div>
<?php }else{
echo "<h2 class='wk_new_msg'>".$helper->__("To BECOME SELLER PLEASE CONTACT TO ADMIN.")."</h2>";
}?>
<script>
function validateNumbers(e)
{
if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
var $wk_jq = jQuery.noConflict();
(function($wk_jq){
$wk_jq( "#special_from_date" ).datepicker({dateFormat: "yy-mm-dd"});
$wk_jq( "#special_to_date" ).datepicker({dateFormat: "yy-mm-dd"});
$wk_jq('#mpselecctall').click(function(event) {
if(this.checked) {
$wk_jq('.mpcheckbox').each(function() {
this.checked = true;
});
}else{
$wk_jq('.mpcheckbox').each(function() {
this.checked = false;
});
}
});
$wk_jq('body').delegate('.mp_edit','click',function(){
var id=$wk_jq(this).attr("data-type");
var dicision=confirm('<?php echo $helper->__(" Are you sure you want to edit this product ? ")?>');
if(dicision==true){
var $type_id=$wk_jq(this).attr('data-type');
window.location = "<?php echo $this->getUrl('mpassignproduct/index/edit/') ?>".concat("id/",id);
}
});
$wk_jq('.mp_delete').click(function(){
var id=$wk_jq(this).attr("data-type");
var dicisionapp=confirm('<?php echo $helper->__(" Are you sure you want to delete this product ? ")?>');
if(dicisionapp==true)
window.location = "<?php echo $this->getUrl('mpassignproduct/index/delete/') ?>".concat("id/",id);
});
$wk_jq('#mass_delete_butn').click(function(e){
var flag =0;
$wk_jq('.mpcheckbox').each(function(){
if (this.checked == true){
flag =1;
}
});
if (flag == 0){
alert("<?php echo $helper->__(' No Checkbox is checked') ?>");
return false;
}
else{
var dicisionapp=confirm('<?php echo $helper->__(" Are you sure you want to delete these product ? ")?>');
if(dicisionapp==true){
$wk_jq('#form-customer-product-delete').submit();
}else{
return false;
}
}
});
})($wk_jq);
function hideReset(product_id)
{
var qtyId='#qty_'+ product_id;
var editLink="#edit_link_"+ product_id;
var updateButton="#update_button_"+ product_id;
var resetButton="#reset_button_"+ product_id;
$wk_jq(qtyId).hide();
$wk_jq(editLink).show();
$wk_jq(updateButton).hide();
$wk_jq(resetButton).hide();
}
function showField(product_id)
{
var qtyId = '#qty_'+ product_id;
var editLink = "#edit_link_"+ product_id;
var updateButton = "#update_button_"+ product_id;
var resetButton = "#reset_button_"+ product_id;
$wk_jq(qtyId).show();
$wk_jq(editLink).hide();
$wk_jq(updateButton).show();
$wk_jq(updateButton).prop('disabled', false);//just in case
$wk_jq(resetButton).show();
return false;
}
function updateField(product_id,assignqty)
{
// alert("Hello! I am an alert box!!");
var qtyId = '#qty_'+ product_id;
var valueId = '#valueqty_'+ product_id;
var updatedqty = '#updatedqty_'+ product_id;
var editLink = "#edit_link_"+ product_id;
var updateButton = "#update_button_"+ product_id;
var resetButton = "#reset_button"+ product_id;
var url = '<?php echo Mage::getUrl('marketplace/marketplaceaccount/updateField/')?>';
$wk_jq(qtyId).toggle();
$wk_jq(editLink).hide();
$wk_jq(updateButton).show();
$wk_jq(resetButton).show();
$qty = $wk_jq(qtyId).val();
jQuery(valueId).html($qty);
hideReset(product_id);
var tmpQty = assignqty+parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: tmpQty},
onComplete: function (transport) {
// alert(tmpQty);
jQuery(priceId).val($price);
jQuery(updatedqty).show().delay(2000).fadeOut();
$updateButton.prop('disabled', false);
}
});
}
</script>
Quantity is working in this file = http://pastebin.com/mByVn3ax

Resources