Ajax file upload with Codeigniter and jQuery Form Plugin - ajax

I'm tying to use jQuery Form Plugin with Codeigniter. When I try to upload, the page is redirected (so the ajax is not working) and nothing is uploaded.
The view from where the form is located look like this:
<form id="upload_form" action="upload/do_upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('#upload_form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
<script type="text/javascript" src="http://localhost/editor/assets/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://localhost/editor/assets/js/jquery.form.js"></script>
</body>
And the controller for the upload is just taken from the Codeigniter manual:
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function do_upload()
{
$config['upload_path'] = './userdata/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error); TODO echo error
}
else
{
$data = array('upload_data' => $this->upload->data());
//$this->load->view('upload_success', $data); TODO echo succes
}
}
}
?>
I'm sure I've just made a little mistake somewhere, could any one see where I went wrong? Thanks in advance!

It looks like you forgot to initialize the form when the DOM is ready.
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#upload_form').ajaxForm(function() {
//rest of your code from the post
});
});

Related

I am send dropzone file through ajax but it show ERROR : "You did not select a file to upload" in Codeigniter 3

View
Image
<!------------------------ Bootstarp Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/bootstrap.min.css');?>" >
<!------------------------ Dropzone Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/dropzone.min.css');?>" >
<label class="form_lable">Select Image </label>
<div class="dropzone-container col-md-6" id="demo-dropzone" >
`your text`
<p >
<div class="dz-default dz-message" >
<div class="dz-icon">
<i class="demo-pli-upload-to-cloud icon-5x"></i>
</div>
<div>
<span class="dz-text">Drop files to upload</span>
<p class="text-sm text-muted">or click to pick manually</p>
</div>
</div>
<div class="fallback">
<input type="file" name="userfile" id="userfile" />
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submit_btn">Submit</button>
</div>
</form>
">
">
">
$('#demo-dropzone').dropzone({
url:"",
autoProcessQueue: false,
addRemoveLinks: true,
multiple:false,
uploadMultiple:true, // uplaod files in a single request
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 500,
acceptedFiles: ".jpg, .png, .jpeg",
init: function() {
var myDropzone = this;
myDropzone.on('maxfilesexceeded', function(file) {
this.removeAllFiles();
this.addFile(file);
});
this.on("removedfile", function(file) {
});
// Update selector to match your button
$("#submit_btn").click(function(e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on("successmultiple", function(file, response) {
if (response && file) {
console.log(response);
}
});
}
});
# Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image_upload extends CI_Controller
{
public function index(){
$this->load->view('image_send');
}
`File upload funxction`
public function do_upload(){
$image_name = $_FILES['file']['name'][0];
$target= $_FILES['file']['tmp_name'][0];
$target_file = basename($image_name);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$custom_file=basename(uniqid().'.'.$imageFileType);
if(is_dir('upload_image')){
echo "is present";
}
else{
mkdir('upload_image');
}
$config['upload_path'] = 'upload_image/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $image_name;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if ($this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
?>
First of all you need to fix your view to have tag to warp out your input.
<form role="form" id="yourFormId" action="#" method="post" enctype='multipart/form-data'></form>
Second, get your form id and set the ajax like this
var frm = $('#yourFormId');
frm.submit(function (e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#yourFileInputID').prop('files')[0];
form_data.append('file', file_data);
$.ajax({
type : "POST",
url : TheUrl,
processData : false,
contentType : false,
cache : false,
data : form_data,
dataType : 'json',
success: function (data) {
//Your Code Goes Here..//
}, error: function () {
// Your Code Goes Here //
}
});
});

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

How to create file uploader in codeigniter?

I see CI documentation to create an image uploader.
here is my Controller :
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$this->load->helper(array('form', 'url'));
$this->load->helper('url');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
echo $this->upload->display_error();
return FALSE;
}
else
{
$data = $this->upload->data();
return TRUE;
}
}
}
and here is my View
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<form action="upload/do_upload" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
But when i upload an image it doesn't upload it and $this->upload->display_error() show nothing(my uploads folder which is in my ci root folder also has 777 permision and i'm using wamp)
Two pointers for you:
<input type="file" name="userfile" size="20" />
Check if the file you're using is not exceeding and the file is being uploaded.
echo $this->upload->display_errors();
See the display_errors with an s.
Suggestions:
In you form's action attribute use a an absolute URL, like:
action="<?php echo base_url() ?>upload/do_upload"
Inside your function do_upload(), do a print_r($_FILEs), to confirm that the file is uploaded correctly with no errors.
I change my function named function do_upload() to function somethingelse() and my problem solved (because i'm calling a built in function)

Displaying progress while waiting for controller in Laravel 4

I've got a form that I want to send by ajax-post to my controller. Meanwhile the HTML is waiting for the generation and saving of the records, I want to display the progress (for now just numbers). I really don't understand why the following code doesn't update <div id="progress"> with Session::get('progress').
Controller:
public function postGenerate() {
// getting values from form (like $record_num)
Session::flash('progress', 0);
$i = 1;
for ($i; $i < $record_num; $i++) {
$record = new Record();
// adding attributes...
$record->save;
Session::flash('progress', $i);
}
$response = Response::make();
$response->header('Content-Type', 'application/json');
return $response;
}
Javascript:
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#form-overview').on('submit', function() {
setInterval(function(){
$('#progress').html( "{{ Session::get('progress') }}" );
}, 1000);
$.post(
$(this).prop('action'),
{"_token": $(this).find('input[name=_token]').val()},
function() {
window.location.href = 'success';
},
'json'
);
return false;
});
});
</script>
#stop
HTML:
#section('content')
{{ Form::open(array('url' => 'code/generate', 'class' => 'form-inline', 'role' => 'form', 'id' => 'form-overview' )) }}
<!-- different inputs ... -->
{{ Form::submit('Codes generieren', array('class' => 'btn btn-lg btn-success')) }}
{{ Form::close() }}
<div id="progress">-1</div>
#stop
Well, that's because {{ Session::get('progess') }} is only evaluated once, when the page is first rendered. The only way to do what you want is to actually make extra AJAX requests to a different URL that reports the progress. Something like this:
Controller
// Mapped to yoursite.com/progress
public function getProgess() {
return Response::json(array(Session::get('progress')));
}
public function postGenerate() {
// getting values from form (like $record_num)
Session::put('progress', 0);
Session::save(); // Remember to call save()
for ($i = 1; $i < $record_num; $i++) {
$record = new Record();
// adding attributes...
$record->save();
Session::put('progress', $i);
Session::save(); // Remember to call save()
}
$response = Response::make();
$response->header('Content-Type', 'application/json');
return $response;
}
JavaScript
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#form-overview').on('submit', function() {
setInterval(function(){
$.getJSON('/progress', function(data) {
$('#progress').html(data[0]);
});
}, 1000);
$.post(
$(this).prop('action'),
{"_token": $(this).find('input[name=_token]').val()},
function() {
window.location.href = 'success';
},
'json'
);
return false;
});
});
</script>
#stop

how to create form for multple image upload in codeigniter

i have created form for multiple image upload.but not working that form.only one image uploading..i want multiple images are to be upload to folder and save image name in database..
My View File
<html>
<head>
<title>Product Upload</title>
<style>
#container
{
width:750px;
margin:0 auto;
//border:5px solid #000000;
}
#container form input[type="text"] {
height:30px;
}
</style>
</head>
<body>
<div id="container" align="center">
<form name="product" action="<?php echo base_url;?>admin/login/upload" method="POST" enctype="multipart/form-data" class="form-horizontal">
<table>
<h3>Add New Product</h3>
<tr><td>Categories</td><td><select name="catid"><option>Categories</option>
<?php if(isset($category_details))
{foreach($category_details as $keys=>$values){ ?>
<option value="<?php echo $values['cat_id'];?>"><?php echo $values['cat_name'];?></option>
<?php }
}?>
</select></td></tr>
<tr>
<td>Product Name:</td><td><input type="text" name="pname"></td></tr>
<tr><td><input type="file" multiple="true" name="userfile" size="20" /></td></tr>
<tr><td><br>Product Image:</td><td><br><input type="file" name="pimage[]" id="pimage" multiple></td></tr>
<tr><td><br>Description:</td><td><br><textarea name="pdescription"></textarea></td></tr>
<tr><td><br>Price:</td><td><br><input type="text" name="price"></td></tr>
<tr><td colspan="2" align="center"><br><input type="submit" name="submit" value="ADD" class="btn btn-primary"></td></tr>
</table>
</form>
</div>
</body>
</html>
My Controller File
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('admin/category_model');
$this->load->model('admin/loginauth_model');
$this->load->model('login_model');
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('cookie');
$this->load->library('encrypt');
$this->load->library('image_CRUD');
}
public function index()
{
$this->load->view('admin/login');
}
public function loadproduct()
{
$category_details=$this->category_model->getCategoryDetails();
$outputdata["category_details"]=$category_details;
$this->load->view('admin/product',$outputdata);
}
public function loginAuth()
{
$this->form_validation->set_rules('email','Enter Email','required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password','Enter your Password','required|trim|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login');
}
else
{
$username=$_POST['email'];
$password=$_POST['password'];
$user_details=$this->loginauth_model->logincheck($username,$password);
//print_r($checkauth);
if($user_details)
{
if($this->session->userdata('adminusername'))
{
$adminusername=$this->session->userdata('adminusername');
$outputdata['username']=$adminusername;
}
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
$this->load->view('admin/dashboard',$outputdata);
}
}
}
public function category()
{
//$this->load->view('admin/category');
$this->form_validation->set_rules('cat_name','category name','required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('cat_desc','category description','required|trim|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/category');
}
else
{
$addcategory=$this->category_model->addcategory($_POST);
if($addcategory)
{
//**************************pending
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
//print_r($outputdata);
$this->load->view('admin/categorylist',$outputdata);
}
}
}
public function categorylist()
{
//echo image_url;
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
$outputdata['image_url']=image_url;
$this->load->view('admin/categorylist',$outputdata);
$this->load->view('admin/category');
}
public function userdetails()
{
$user_details=$this->login_model->userdetails();
$outputdata['user_details']=$user_details;
$this->load->view('admin/userdetails',$outputdata);
}
public function upload()
{
$productname=$_POST["pname"];
$description=$_POST["pdescription"];
$price=$_POST["price"];
$catid=$_POST["catid"];
$name_array = array();
echo $count = count($_FILES['pimage']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['pimage']['name']=$value['name'][$s];
$_FILES['pimage']['type'] = $value['type'][$s];
$_FILES['pimage']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['pimage']['error'] = $value['error'][$s];
$_FILES['pimage']['size'] = $value['size'][$s];
$config['upload_path'] = FCPATH.'img/product_uploads/original/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|GIF|PNG|JPG|JPEG';
$config['max_size'] = '100';
$config['max_width'] = '150';
$config['max_height'] = '180';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
//$products=$this->category_model->addproduct($catid,$productname,$description,$imagename,$imagesize,$price,$path);
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
//echo FCPATH;
//$productname=$_POST["pname"];
// $description=$_POST["pdescription"];
// $price=$_POST["price"];
//$catid=$_POST["catid"];
// $path = FCPATH.'img/product_uploads/original/';
// $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP","PNG");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
// $imagename = $_FILES['pimage']['name'];
// $imagesize = $_FILES['pimage']['size'];
// list($txt, $ext) = explode(".", $imagename);
//$products=$this->category_model->addproduct($catid,$productname,$description,$imagename,$imagesize,$price,$path);
//print_r($products);
// $tmp = $_FILES['pimage']['tmp_name'];
//if(move_uploaded_file($tmp, $path.$imagename)) {
// $product_details=$this->category_model->getProductDetails();
//print_r($product_details);
//if(isset($products)){
//echo "aa";
// $this->loadproduct();
//}
// }
//else
// {
//echo "Image Upload Failed.";
//}
}
public function logout()
{
$newdata = array(
'adminuser_id' =>'',
'adminusername' =>'',
'adminemail' => '',
'logged_in' => FALSE,
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
$this->index();
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
You can't just add a multiple attrinbute to <input type="file" />, that's not going to work.
You'll have to use a third-party module/plugin, like Uploadify, to get this functionality running.
You could also check this tutorial on how to integrate Uploadify in CodeIgniter (although I can't see anything CodeIgniterish in your code, but you still tagged the question as CI relevant)
a) Instead of writing this <input type="file" multiple="true" name="userfile" size="20" /> write <input type="file" name="userfile[]" size="20" />
b) Inside your controller you can do something like this:
$files = $_FILES;
$count = count($_FILES['userfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload();
$image_data = $this->upload->data();
}
Use this to open your upload form :
echo form_open_multipart('admin/do_upload');
After put one or more :
<input type="file" name="name" size="20" />
And use a function like that :
public function do_upload() {
$config['upload_path'] = './assets/images/upload/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/images', $error);
} else {
$data = array('upload_data' => $this->upload->data());
}
}

Resources