You did not select a file to upload, file upload error in Codeigniter - codeigniter

I'm trying to add singer information with image. the information can be successfully added without image but if i try to insert data with image, error occurred with "You did not select a file to upload" message.
My controller function is this...
public function add_edit_singer($id = '')
{
if($this->input->post('save_singer_info')){
$post=$this->input->post();
$add=array(
'name'=>$post['sname'],
'bio'=>$post['bio']
);
$img1=$_FILES['photo']['name'];
if($img1){
$config['upload_path'] = 'images/singer/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$error = $this->upload->display_errors();
$this->session->set_flashdata('info',$error);
redirect('admin/singer_manager');
}
$data = array('upload_data' => $this->upload->data());
$image = $data['upload_data']['file_name'];
$add['image']=$image;
}
else{
$add['image']='no_image.jpg';
}
$table='tbl_singer';
if($this->singer_manager->add($add,$table)){
$this->session->set_flashdata('info',"Artist/Band Information Added Successfully.");
redirect('admin/singer_manager');
}
else{
redirect('admin/singer_manager');
}
}
else{
$data['main_content']='admin/singer/add_edit_singer_view';
if($id != '')
$data['editdata'] = $this->common_model->get_where('tbl_singer', array('id' => $id));
$this->load->view('admin/include/template_view',$data);
}
}
my Model function is...
function add($data,$table){
$name = $data['name'];
$res = $this->db->insert($table,$data);
if($res)
{
return true;
}
else
{
return false;
}
}
and my Form is...
<form role="form" enctype="multipart/form-data" action="<?php echo base_url('admin/singer_manager/add_edit_singer/' . $id); ?>"
method="post"
id="user_form">
<table class="table table-hover">
<tr>
<td>Singer Name</td>
<td>
<input type="text" class="form-control required" name="sname"
value="<?php if (isset($name)) {
echo $name;
} ?>"/>
</td>
</tr>
<tr>
<td>Bio</td>
<td>
<textarea class="form-control required" name="bio">
<?php if (isset($bio)) {
echo $bio;
} ?>
</textarea>
</td>
</tr>
<tr>
<td>Image</td>
<td>
<?php if (isset($image)) {?>
<div class="row">
<div class="col-xs-6 col-md-4">
<a href="<?php echo base_url().'images/singer/'.$image;?>" class="thumbnail">
<img src="<?php echo base_url().'images/singer/'.$image;?>" width="120" height="140" id="img_prev" />
</a>
</div>
</div>
<?php
} ?>
<input type="file" name="photo" size="20" />
</td>
</tr>
<tr>
<td colspan="2">
<?php if (isset($id)) { ?><input type="hidden" name="id" value="<?php echo $id; ?>" /><?php } ?>
<input type="submit" class="btn btn-success" id="btn_save" name="save_singer_info"value="Save"/>
<input type="reset" class="btn btn-info" id="reset"/>
<input type="button" class="btn btn-danger" value="Cancel"onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>

change
$this->upload->do_upload()
to
$this->upload->do_upload('photo')
may be it solve the problem

Related

ajax only works once a refresh

I was doing a cart section where you can change your product quantity, at first i did it with a normal form, but i change it to ajax because i want to the page doesn´t need to refresh at all to show you your new quantity with your new price and your new total, so i did the following:
$('.actform').on('submit', function(ev) {
var id2 = $(this);
$.ajax({
type: $(id2).attr('method'),
url: $(id2).attr('action'),
data: $(id2).serialize(),
success: function(data) {
$('.container').load(' .container');
},
error: function() {
alert('Ha ocurrido un error');
}
});
ev.preventDefault();
});
It was all okay when you change 1 product for first time, but the second time the forms submits like it doesn´t have ajax, to fix this problem i replaced $('.container').load(' .container'); to $('.container').load(window.location.reload(false)); and it works, but i wanna know if there is another way to do it because this reload stutters a bit the page reload and it looks weird
cart.php whithout ajax (if you need to see):
<main id="main" class="main">
<?php if(!empty($_SESSION['cart'])){ ?>
<div class="container">
<h2 class="carrito-title">Mi Carrito</h2>
<div class="container2">
<div class="container-cart">
<table>
<thead>
<tr>
<th class="product-image">Imagen</th>
<th class="product-name">Producto</th>
<th class="product-price">Precio</th>
<th class="product-quantity">Cantidad (Modificar)</th>
<th class="product-total">Total</th>
<th class="product-remove">Eliminar</th>
</tr>
</thead>
<tbody>
<?php
$total= 0;
foreach($_SESSION['cart'] as $indice=>$producto){
$ID = $producto['ID'];
$select_products = $connect->prepare("SELECT * FROM `productos` WHERE id=$ID") or die('query failed');
$select_products->execute();
$list_products = $select_products->fetchAll(PDO::FETCH_ASSOC);
foreach($list_products as $product){
$nombre= $product['nombre'];
$precio= $product['precio'];
$codigo = $product['codigo'];
$imagen = "media/productos/$codigo.png";
?>
<tr>
<td class="product-image">
<img src="<?php echo $imagen?>" alt="<?php $nombre?>">
</td>
<td class="product-name">
<h2 class="name"><?php echo $nombre?></h2>
</td>
<td class="product-price"><h2 class="precio">$<?php echo number_format($precio, 0, ',', '.') ; ?></h2></td>
<td class="product-quantity">
<form action="backend/actProduct.php" method="post" class="actform" id="<?php echo $ID ?>">
<div class="cantidad">
<div class="cantidad-container">
<input type="hidden" name="id" min="1" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<input type="number" class="nro updateCant" onchange="btnCart.click()" name="cantidadupd" value="<?php echo $producto['CANTIDAD'];?>">
<button name="btnCart" value="Update" type="submit" class="actualizar"><i class="fa-solid fa-rotate"></i></button>
</div>
</div>
</form>
</td>
<?php
$sub_total = $precio * $producto['CANTIDAD'];
$total = $total + $sub_total;
?>
<td><h2 class="subtotal">$<?php echo number_format($sub_total, 0, ',', '.'); ?></h2></td>
<td>
<form action="backend/deleteProduct.php" method="post">
<input type="hidden" name="id" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<button class="delete" name="btnCart" type="submit" value="Remove" onclick="return confirm('Seguro que quieres eliminar este artículo?');">X</button>
</form>
</td>
</tr>
<?php
}};
?>
</tbody>
</table>
</div>
<?php if(isset($_SESSION['cart'])){ ?>
<div class="nocart">
<div class="final">
<h5 class="final-price preciofinal">Precio sin Impuestos: $<?php echo number_format($total, 0, ',', '.');?></h5>
<form action="backend/emptyCart.php" method="post" class="emptyform" id="<?php echo $ID ?>">
<input type="hidden" name="empty">
<button name="btnCart" type="submit" class ="vaciar" value="Empty" onclick="return confirm('¿Desea vaciar el carrito?');">Vaciar carrito</button>
</form>
</div>
<?php
if ($rol=='representante'){
?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<a class="checkout-btn" href="clientes.php">Seleccionar cliente</a>
</div>
<?php
}else{?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<form action="backend/fincompra.php" method="post" onsubmit="showLoad()">
<button name="btnFinCart" class ="checkout-btn" onclick="return confirm('¿Está seguro que desea finalizar la compra?');" value="Fin" >Finalizar compra</button>
</form>
</div>
<?php
}
?>
</div>
</div>
<?php }?>
</div>
<?php }else{
echo '
<div class="nosesion">
<h2 class="cartvacio">El carrito esta vacío</h2>
<a class="comprar-btn" href="productos.php">Comprar ahora</a>
</div>
';
}?>
</main>

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

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

I want to upload an image with first name and last name without refreshing the page in codeigniter

This is my controller
function edit_profile() {
// if (isset($_POST['submit']))
//{
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$name = $session_data['name'];
$uploaddata = null;
$config['upload_path'] = './assets/uploads/userpic';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$Img_name= strtotime(date("d-m-y H:i:s")).".jpg";
//$Img_name= strtotime(date("d-m-y H:i:s"));
$config['file_name']= $Img_name ;
$config['overwrite'] = "true";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('documents')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploaddata = array('upload_data' => $this->upload->data());
}
$upload_data = $this->upload->data();
$file_name = $name;
$filepath1= $config['upload_path'];
if(!is_uploaded_file($_FILES['documents']['tmp_name'])) {
echo 'No upload';
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname')
);
}else
{
echo "file uploaded";
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname'),
'filepath'=> $Img_name,
'filename'=>$file_name
);
}
$this->load->model('update_model');
$this->update_model->update_entry($id, $data); //passing control to update_model
$session_data['name'] = $this->input->post('firstname');
$this->session->set_userdata('logged_in', $session_data); //settting sesssin values
if( $data)
{
$data['message']="Image Uploaded Successfully";
$this->load->view('endusers/endemp_edit_profile_view',$data);
}
//redirect('endusers/end_emp_home');
//}
}
This is my view
<?php echo form_open_multipart('endusers/editprofile/edit_profile');?>
<table width="auto" border="1" style="border-color: #bce8f1;"class="table table-bordered" >
<tbody>
<tr>
<td colspan="2"><input type="text" class="txt-field uname" name="firstname" placeholder="first name" required></td>
</tr>
<! ------ <tr>
<td colspan="2"><input type="text" class="txt-field pass" name="lastname" placeholder="last name" required ></td><br>
</tr>
<tr>
<tr>
<td valign="top">
<label for="curtexp" style="margin-top: 20px;padding-right: 7px;margin-left: 11px;"> Upload a Profile Picture </label> <label class="error" ></label>
<input type="file" name="documents" size="40" / style="margin-left: 9px;" placeholder="Profile Picture"><br><br>
</td>
</tr>
<tr>
<td colspan="8" style="text-align:center">
<br />
<div class="ee">
<input type="submit" class="btn btn-primary" value="Update" class="buttonmy2" / style="float: left; margin-bottom: 17px;">
<input type="Reset" class="btn btn-primary" value="Reset" class="buttonmy2" / style="float: left;margin-left: 10px;">
<?php echo validation_errors(); ?>
</div>
</td>
</tr>
</tbody>
</table>
</form>
This is my code in codeigniter for uploading a profile pic but it takes ma to log out to see the uploaded image .I want tom upload a image without logging out of my account and may be jusr refreshing the page
--This Jquery plugin will solve your problem
--More help http://malsup.com/jquery/form/#getting-started
<script src="http://malsup.github.com/jquery.form.js"></script>
$("#form_id").on('submit', (function (e) {
var options = {
url:'your URL', // target element(s) to be updated with server response
success:function(data){
alert('submitted');
}
$(this).ajaxSubmit(options);
e.preventDefault();
}));
Comment me if you need help...

codeIgniter form validation not working with file upload option

I am trying this code but it is not working with file upload.
When there is no file uploading field it works fine but with file upload its not working.
Please help me.
form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('emp'); ?>
<form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data">
<table border="1">
<tr>
<th>Name</th>
<td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td>
</tr>
<tr>
<th>Email </th>
<td><input type="text" name="email" value="<?php echo $email; ?>"/></td>
</tr>
<tr>
<th>Address</th>
<td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
</tr>
<tr>
<th>Phone</th>
<td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td>
</tr>
<tr>
<th>Photo</th>
<td><input type="file" name="userfile" /></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/>
<input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/>
</form>
</body>
Here is the controller code.
Emp.php
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name','required','callback_username_check');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'required');
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1800';
$config['max_width'] = '1924';
$config['max_height'] = '1924';
$new_name = time().$_FILES['userfile']['name'];
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->emp_model->add_data();
$query['value']=$this->GetAll();
}
}
try this
if (null != ($_FILES['userfile']['tmp_name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}
And this function for validation
public function checkPostedFiles()
{
$file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
$file_name = str_replace(" ", "", $file_name);
if (isset($_FILES['userfile']) && !empty($file_name)) {
$allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
$extension = end(explode(".", $file_name));
if (in_array($extension, $allowedExts)) {
return true;
} else {
$this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
return false;
}
} else {
$this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
return false;
}
}
Check this sample code for image uploading :
Form :
<form method="post" action="" id="upload_file">
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Profile Picture</label>
<input type="file" id="userfile" accept="image/*" name="userfile">
<p class="help-block">Requested size : 215*215</p>
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
</div>
</div>
</form>
Include this js in your view.
Js for form submission
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url:'<?php echo base_url(); ?>profile/upload_file',
type: "POST",
fileElementId :'userfile',
success: function() {
alert("file uploaded!");
}
});
return false;
});
});
In controller
$userid = $session_data['id'];
$file_element_name = 'userfile';
$pathToUpload = '/var/www/html/uploads/' . $userid;
if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);
if (!$create)
return;
}
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(
'userPhoto' => $data['file_name']
);
$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data);
}
//#unlink($_FILES[$file_element_name]);

Resources