Reputation: 353
Please be nice..
It's been two days that I'm struggling with this, So I decided to post it.
What I have :
A fresh CodeIgniter installation on my localhost (Windows), with one controller and one view. Everything is working perfectly.
What I want to do :
Upload an image using AJAX with CodeIgniter without reloading the page.
My controller (Test.php) :
class Test extends CI_Controller {
public function index()
{
# Started working with file upload.
$validFiles = array(
'upload_path' => './assets',
'allowed_types' => 'jpg|png|gif',
'max_size' => 250000
);
$this->load->library('upload', $validFiles);
if ($this->upload->do_upload('newsphoto'))
{
echo "Image Uploaded Successfully!";
}
else
{
echo $this->upload->display_errors();
}
}
public function upload()
{
$this->load->helper('form');
$this->load->view('test');
}
}
My View (test.php) :
<html>
<body>
<div class="CustomForm">
<?php echo form_open_multipart(base_url().'test', array('class' => 'newsForm')); ?>
<div class="row">
<input type="file" class="InputField" name="newsphoto" value="">
<input type="text" class="InputField" name="title" value="">
<textarea name="news" class="InputField" cols="30" rows="10"></textarea>
<button>Go</button>
</div>
<?php form_close(); ?>
</div>
</body>
<html>
My JS script (It's in the view I separated it to make it easy to read) :
<script type="text/javascript">
$(document).ready(function () {
var form = $('form.newsForm');
form.on('submit', function (c) {
c.preventDefault();
var data = new FormData();
$.each($('form.newsForm :input'), function(i, fileds){
data.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('form.newsForm input[type=file]')[0].files, function (i, file) {
data.append(file.name, file);
});
$.ajax({
url: '<?php echo base_url(); ?>/test',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (c) {
var msg = $('div.jsMessage');
msg.empty();
msg.html(c);
}
});
return false;
});
})
</script>
What I'm getting now :
I'm getting a simple upload that works correctly, as the picture shows.
I think that my ajax code doesn't run, and I'm not sure it'll work if it does. Any help?
Thank you in advance!
Upvotes: 1
Views: 4690
Reputation: 140
Try Ajax File Uploader : github
Below you can find a working example for your scenario.
routes.php
$route['form'] = 'Test/upload';
$route['upload'] = 'Test';
config.php
The code mentioned helps maintaining the configuration of base url as such for both localhost and the live server. You don't have to update the
$config['base_url']
, when you move the files to live server. You can find that piece of code below.
$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = "$root";
autoload.php
$autoload['helper'] = array('url');
controller - Test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller
{
public function index()
{
# Started working with file upload.
$validFiles = array(
'upload_path' => 'assets',
'allowed_types' => 'jpg|png|gif',
'max_size' => 250000
);
$this->load->library('upload', $validFiles);
if ($this->upload->do_upload('newsphoto'))
{
$return['msg']='Image Uploaded Successfully!';
echo json_encode($return);
}
else
{
echo $this->upload->display_errors();
}
}
public function upload()
{
$this->load->helper('form');
$this->load->view('test');
}
}
View : test.php
Have you used jquery library in your view ? using that would make the JS work.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="<?php echo base_url() ?>assets/JS/ajaxfileupload.js"></script>
</head>
<body>
<div class="CustomForm">
<?php echo form_open_multipart(base_url().'index.php/upload', array('class' => 'newsForm')); ?>
<div class="row">
<input type="file" id="newsphoto" class="InputField" name="newsphoto" value="">
<input type="text" id="title" class="InputField" name="title" value="">
<textarea name="news" id="news" class="InputField" cols="30" rows="10"></textarea>
<button> Upload</button>
</div>
<?php form_close(); ?>
</div>
<script type="text/javascript">
$(document).ready(function () {
var form = $('form.newsForm');
form.on('submit', function (c) {
c.preventDefault();
var data = new FormData();
$.each($('form.newsForm :input'), function(i, fileds){
data.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('form.newsForm input[type=file]')[0].files, function (i, file) {
data.append(file.name, file);
});
var param = {'title':$('#title').val(),'news':$('#news').val()};
$.ajaxFileUpload
(
{
url:'<?php echo base_url(); ?>index.php/upload',
secureuri:false,
data: param,
fileElementId:'newsphoto',
dataType: 'json',
beforeSend: function(){
console.log("I'm sending AJAX.");
//display loading?
},
success: function (data, status)
{
alert(data.msg);
},
error: function (data, status, e)
{
alert(e);
}
}
);
return false;
});
});
</script>
</body>
<html>
Upvotes: 1