Ajax image upload refresh the page? - php

I am wondering that , why my page is getting refresh while i am using ajax to upload image, i tried to debug the problem, but did'nt find,
Here is the Controller function,
public function uploadImage() {
if(isset($_FILES['header_image'])) {
$config['upload_path'] = 'public/images/global/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'b_'.random_string('alnum', 5);
$this->upload->initialize($config);
if($this->upload->do_upload('header_image')) {
echo json_encode(array('status'=>"1", 'image_url'=>$this->upload->file_name));
} else {
$upload_error = array('error' => $this->upload->display_errors());
echo json_encode(array('status'=>"0",'upload_error'=>strip_tags($upload_error['error'])));
}
exit;
}
$this->template->render();
}
While my view uploadImage.php is look like,
$(document).ready(function() {
$('#header_image').on('change', function(){
$("#frm_global").ajaxForm({
success: function(data) {
res = $.parseJSON(data);
if(res.status == 1){
var html = "<img src='<?=base_url();?>path/"+res.image_url+"' class='preview' width='100' height='100' />";
html+= "<input type='hidden' id='image_url' name='image_url' value='"+res.image_url+"' >";
$("#preview").html(html);
$("#frm_global").ajaxFormUnbind();
}
if(res.status == 0){
$("#frm_global").ajaxFormUnbind();
}
}
}).submit();
});
});
<form name="frm_global" id="frm_global" enctype="multipart/form-data">
<div id="preview" style="float:left">
</div>
<div style="float:left">
<div style="margin-top:25px">
<input type="file" name="header_image" id="header_image"/>
<input style="margin-left:100px" onclick="" type="image" id="upload_header" src="any path" />
</div>
</div>
</form>

Sorry i think i didn't get your question properly.
But for submitting you can try like this
$("#theForm").ajaxForm({
url: 'server.php',
type: 'post',
success:function(data)
{
//do what you want to
}
});
may it helps you

Related

how to pass image from controller to view with CodeIgniter Imagick

I was working with CodeIgniter php, and using Imagick for some image manipulation. Now I want to upload image and after image manipulation e.g Image equalizing, I want to pass or load the equalized image from controller to view. The image is equalized and uploaded to a path, but I am unable to load the output equalized image to view page. So, kindly guide how to handle this problem?
Controller Code:
class Equalize extends CI_Controller {
public function equalize_image() {
if (isset($_FILES["userfile"])) {
$tmpFile = $_FILES["userfile"]["tmp_name"];
$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);
$fileName = uniqid(rand(), true) . "." . $ext;
list($width, $height) = getimagesize($tmpFile);
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
$image = new Imagick($tmpFile);
$image->equalizeImage();
$image->writeImage(FCPATH.'/assets/images' . "/" . $fileName);
header("Content-Type: image/jpeg");
echo $image;
}
}
}
View Code:
<label>Input Image</label>
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type='file' name="userfile" size="20" onchange="readURL(this);"/>
<label>Orignal Image</label><br>
<img id="blah" src="#" alt="" />
<label>Equalized Image </label>
<div id="result">
</div>
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#userfile').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>Equalize/equalize_image",
//base_url() = http://localhost/tutorial/codeigniter
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data)
{
$('#result').html(data);
}
});
}
});
});
</script>
</body>
With this code I am facing this output: https://imgur.com/85vMove. How to load the image in view?
Take 1
Just pass the newly created image url to the ajax success function via json and modify the img src to that url.
HTML:
<label>Input Image</label>
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type='file' name="userfile" size="20" onchange="readURL(this);"/>
<label>Orignal Image</label><br>
<img id="blah" src="#" alt="" />
<label>Equalized Image </label>
<div id="result">
<img src="http://via.placeholder.com/300x400">
</div>
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function () {
$('#upload_form').on('submit', function (e) {
e.preventDefault();
if ($('#userfile').val() == '')
{
alert("Please Select the File");
} else
{
$.ajax({
url: "<?php echo base_url(); ?>Equalize/equalize_image",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (data)
{
if (data.success == true) {
$('#result').find('img').attr('src', data.file);
} else {
alert(data.msg);
}
}
});
}
});
});
</script>
</body>
PHP:
try {
if (!isset($_FILES["userfile"])) {
throw new Exception('No file uploaded.');
}
$tmpFile = $_FILES["userfile"]["tmp_name"];
$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);
$fileName = uniqid(rand(), true) . "." . $ext;
list($width, $height) = getimagesize($tmpFile);
if ($width == null && $height == null) {
throw new Exception('An error occured.');
}
$image = new Imagick($tmpFile);
$new_file = "assets/images/{$fileName}";
$image->equalizeImage();
$image->writeImage(FCPATH . '/' . $new_file);
echo json_encode(array('success' => true, 'file' => base_url($new_file)));
} catch (Exception $e) {
echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
}
Take 2
This is the only way you can download the file without having it saved on the server.
class Test extends CI_Controller {
public function index() {
$this->load->view('test');
}
public function eq() {
try {
if (!isset($_FILES['userfile'])) {
throw new Exception('No file uploaded.');
}
$file_error = $_FILES['userfile']['error'];
if ($file_error !== 0) {
throw new Exception('Error uploading: Code ' . $file_error);
}
$tmp_file = $_FILES['userfile']['tmp_name'];
list($width, $height) = getimagesize($tmp_file);
if ($width == null && $height == null) {
throw new Exception('An error occured.');
}
$image = new Imagick($tmp_file);
$image->equalizeImage();
$encoded_file = base64_encode($image->getimageblob());
echo json_encode(array('success' => true, 'type' => $image->getimageformat(), 'file' => $encoded_file));
} catch (Exception $e) {
echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
}
}
public function download() {
$contents = $this->input->post('image_contents');
$extension = $this->input->post('extension');
if (is_null($contents) || is_null($extension)) {
show_error('Image contents empty');
}
$name = 'equalized_image.' . strtolower($extension);
$contents = base64_decode($contents);
$this->load->helper('download');
force_download($name, $contents);
}
}
HTML:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#original-image')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function () {
$('#download').hide();
$('#upload_form').on('submit', function (e) {
e.preventDefault();
if ($('#userfile').val() == '')
{
alert("Please Select the File");
} else
{
$.ajax({
url: "/neou_cms/test/eq",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (data)
{
console.log(data);
if (data.success == true) {
var image_content = 'data:image/' + data.type + ';base64,' + data.file;
$('#eq-image').attr('src', image_content);
$('#image_contents').attr('value', data.file);
$('#extension').attr('value', data.type);
$('#download').show();
} else {
alert(data.msg);
}
}
});
}
});
});
</script>
</head>
<body>
<form method="post" id="upload_form" enctype="multipart/form-data">
<table border="1">
<tr>
<td colspan="2"><input type="file" name="userfile" size="20" onchange="readURL(this);"></td>
</tr>
<tr>
<td>Original Image</td>
<td>Equalized Image</td>
</tr>
<tr>
<td>
<img id="original-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
</td>
<td>
<img id="eq-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info">
</td>
</tr>
</table>
</form>
<form method="post" action="/neou_cms/test/download">
<input type="hidden" value="" name="image_contents" id="image_contents">
<input type="hidden" value="" name="extension" id="extension">
<input type="submit" name="download" id="download" value="Download Image">
</form>
</body>
</html>

You did not select a file to upload(codeigniter)

I am trying to upload a pic for which I have used the following code.
HTML:(I want that pic to be uploaded without submitting the form.)
<form id="chapThumb" method="post" action="<?php echo base_url();?>index.php/Admin/createChapter" enctype="multipart/form-data">
<input type="file" name="thumbpic" id="thumbpic">
<p class="FS12">Upload a thumbnail Image for the Chapter</p>
<input type="text" class="form-control" name="chname" placeholder="Enter chapter name"><br>
<input type="button" class="form-control" name="thumb" value="Upload" id="thumb">
<input class="dp-btn2" type="submit" value="Create" name="submit">
</form>
JQuery:
$(document).ready(function(){
$("#thumb").on('click',function(){
var x = $("#thumbpic").val();
console.log('x:'+x);
jQuery.ajax({
type: 'POST',
dataType: "json",
url: "<?php echo base_url();?>index.php/Admin/createChapterThumb",
data: {"thumbpic":x},
success:function(response){
console.log("response"+response);
var msg = response.message;
var stat = response.status;
var da = response.da;
console.log('msg:'+msg+',stat:'+stat+',da:'+da);
if(stat == 'success'){
//some code
}
else{
//some code
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
});
});
Controller:
public function createChapterThumb(){
if($this->input->is_ajax_request()) {
$this->load->model('DPModel');
$config['upload_path'] = 'uploads/chapters/thumbs/temp';
$config['file_name'] = 'chapThumb';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('thumbpic'))
{
$data['status'] = 'error';
$data['message'] = $this->upload->display_errors();
echo json_encode($data);
}
else
{
$data['status'] = 'success';
$data['message'] = $this->upload->data();
echo json_encode($data);
}
exit;
}
//$res = $this->customerModel->insertChapter();
}
When upload button is clicked am getting the following error in console:
msg:You did not select a file to upload.,stat:error
Change the line $config['upload_path'] = 'uploads/chapters/thumbs/temp'; in controller function to below.
$config['upload_path'] = './uploads/chapters/thumbs/temp/';
Also, set the file permission of the folder to 777.

Update Image from database using ajax, jquery,and PHP not working

I wanna update profile picture of user that has logged in to my website.
I use ajax, jquery, php to update data, in order to update data without refresh the page.
This code just working to upload image into folder, but when I use this code to update image from database, it only sent null into database.
jquery and ajax script
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
And it's the php syntax
upload.php
<?php
require_once 'koneksi.php';
if($_POST)
{
$id_user= $_POST['id_user'];
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = '../images/ava/'; // upload directory
try {
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
else
{
echo 'invalid';
}
$update = $db_con->prepare("UPDATE tb_users SET image=:img WHERE id_user=:id_user");
$update->bindparam(":id_user", $id_user);
$update->bindparam(":img", $image);
$update->execute();
$count = $update->rowCount();
if($count>0) {
echo "success";
}else {
echo "can't update!";
}
}
}catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML syntax
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<script type="text/javascript">
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
</script>
I found two errors in your code in proses.php
<?php include 'koneksi.php';
$foto = #$_POST['foto'];
$id = #$_POST['id'];
$update = $db->prepare("UPDATE tb_users SET foto=:foto WHERE id=:id");
$update>bindParam(":id", $id);
$update->bindParam(":foto", $foto);
$update->execute();
if($update->rowCount() > 0) {
echo "success";
}
?>
the error messages would be very helpful, but at the very least you are missing a - in $update>bindParam(":id", $id);, so it should be $update->bindParam(":id", $id);
you did the same thing again with $update>rowCount() should be $update->rowCount()
update: I see you edited your question to fix those, but still haven't posted the errors you're receiving. Were those tpyos in your question, or are you progressively fixing your code?
still, it looks like you're missing a closing curly brace } in this statement:
if($update>rowCount() > 0) {
echo "success";
?>
also, why are you silencing notices with #$_POST? if those values are empty, then do you really want to be updating the table?

Using Ajax to upload file in codeigniter

Well..I'm new to codeigniter. And I'm stuck on this problem from days!
I read many questions and answers telling about file upload using ajax. But I can't find a specific solution to my problem.
There is the View :
<?php echo form_open_multipart('upload/upload_cover', array("id" => "upload_file"));?>
<input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
<br /><br />
<input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload">
</form>
Controller : Upload, method upload_cover
public function upload_cover() {
$file = $_FILES['userfile']['tmp_name'];
$userid = $this->session->userdata('userid');
$ext = end(explode('.', $_FILES['userfile']['name']));
$_FILES['userfile']['name'] = "$userid.$ext";
$config['upload_path'] = './img/cover/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$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());
$data['body'] = 'body_profile';
$data['error'] = $error;
$this->load->view('include/template_profile', $data);
}
else {
$cover = "$userid.$ext";
echo $cover;
$this->load->model('dbconnect');
$this->dbconnect->editCover($userid, $cover);
//$this->index();
$data = $this->upload->data();
$image_path = $data['full_path'];
if(file_exists($image_path))
{
echo json_encode($image_path);
}
//redirect('homepage/');
//echo base_url()."img/cover/".
}
Now my problem is... This code is working without ajax... I want to write this using Ajax, so that image is uploaded and shown in its div on clicking Upload button.
So what should I pass in data of ajax request to use the above controller method itself?
Thank you..
Well.. you need jquery.form this way:
$(document).ready(function() {
var $form = $('#myform');
var $btn = $('#submit'); // upload button
$btn.click(function() {
// implement with ajaxForm Plugin
$form.ajaxForm({
beforeSend: function() {
// xyz
},
success: function(img_url) {
$form.resetForm();
alert(img_url);
//$myimage.attr('src', img_url);
},
error: function(error_msg) {
alert('error:' + error_msg);
}
});
});
});
also you need return (or stored in json) an url from php :)
View :
<div class="upload" id="upload" style="display:none">
<form id="form-id" action="#" enctype="multipart/form-data" method="POST">
<input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
<br /><br />
<input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload" />
</form>
</div>
Controller : Upload, method upload_cover
public function upload_cover() {
$userid = $this->session->userdata('userid');
$config['upload_path'] = 'C:\wamp\www\Twitter_Project\img\cover';
$config['upload_url'] = base_url().'files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000KB';
$config['max_width'] = '4096';
$config['max_height'] = '2160';
$config['overwrite'] = TRUE;
$config['file_name'] = $userid;
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
//$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
echo "error";
}
else
{
//$username = $this->session->userdata('username');
$ext = end(explode('.', $_FILES['userfile']['name']));
$data = "$userid.$ext";
//$data = array('upload_data' => $this->upload->data());
$this->load->model('dbconnect');
$this->dbconnect->editCover($userid, $data);
//$this->load->view('upload_success', $data);
echo json_encode($data);
}
#unlink($_FILES['userfile']);
echo 'unlinked user file';
}
Ajax method :
$('#form-id').on('submit', function(event){
event.preventDefault();
var data = new FormData($(this)[0]);
$.ajax({
url: base + 'upload/upload_cover',
type: 'POST',
dataType: 'json',
data: data,
processData: false,
contentType: false,
cache: false
}).done(function(data) {
if(data !== 'error'){
console.log("success");
console.log(data);
var path = base + 'img/cover/' + data;
console.log(path);
console.log( $('#sp1')[0].src);
//$('#sp1')[0].src = path;
$('#sp1').attr('src',path);
}
else{
alert("Cannot upload your cover picture. Please try again.");
}
})
});
This is a working solution, one will have to write only the model method separately.
Now, I dont want to get the previously saved image name to unlink so here I overwrite the image. Is there a way to overwrite the cached image other than changing filename?

How to upload an image using ajax and preview it

Am trying to upload an image to images folder using ajax but its not working
when i choose an image then the image should upload to my folder in local hard drive and further i will use that.
Please help me
My Code is :
SCRIPT
$(document).ready(function() {
$('#pathAbout,#path,#pathWork').change(function(){
if($(this).val() !=""){
$.ajax({
type: "POST",
url: "imageLoad.php",
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
success: function(msg){
alert(msg);
}
});
}
});
});
</script>
HTML
<form method="POST" action="tabs.php?page=HOME" enctype="multipart/form-data">
<table>
<tr>
<td><label>Choose Image</label></td>
<td><input type="file" id ="pathAbout" name="imgPath" /></td>
</tr>
</table>
</form>
PHP
if(!empty($_POST)) {
if((isset($_POST['name']) && $_POST['name'] != '') || (isset($_POST['type']) && $_POST['type'] != '') ||(isset($_POST['tmp_name']) && $_POST['tmp_name'] != ''))
{
$name = $_POST['name'];
$type = $_POST['type'];
$tmp_name = $_POST['tmp_name'];
$extension = strtolower(substr($name, strpos($name , '.') +1));
if(($extension == 'png' || $extension == 'jpeg' || $extension == "jpg")&&($type == "image/png" || $type == "image/jpeg" || $type == "image/jpg"))
{
$location = 'images/';
if(move_uploaded_file($tmp_name,$location."$name"))
{
echo "Loaded";
} else {
echo "Error occured";
}
} else {
echo "Unsupported file format";
}
} else {
echo "Please choose a file";
}
} else {
echo "No Information found";
}
This is my code but nothing is happening when i choose a file
If you want you can use Uploadify here you can also see demo and for sample code for eg-
$(function() {
$("#file_upload").uploadify({
'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onUploadStart' : function(file) {
$("#file_upload").uploadify("settings", "someOtherKey", 2);
}
});
});
$("#image_upload2").uploadify(uploadifyBasicSettingsObj);
uploadifyBasicSettingsObj.onUploadSuccess = function(file, data, response)
{
$('.tempImageContainer2').find('.uploadify-overlay').show();
/* Here you actually show your uploaded image.In my case im showing in Div */
$('.tempImageContainer2').attr('style','background- image:url("../resources/temp/thumbnail/'+data+'")');
$('#hidden_img_value2').attr('value',data);
}
The HTML code:
<div class="boxWrapper tempImageContainer2" data-image-container-id="2">
<input type="file" accept="gif|jpg" name="image2" style="" id="image_upload2"/>
<input type="hidden" value="" name="image[]" id="hidden_img_value2">
<input type="hidden" name="upload_path" value="" id="upload_path2" class="upload_path">
<div class="uploadify-overlay">Change</div>
<a class="remove-pic-link" href="javascript:void(0)" style="display:none">Remove</a>
</div>
It is not possible to upload an image directly using AJAX, but there are some libraries that create dynamic iframes to accomplish this.
Check out this one, which I have used in several projects: valums.com/ajax-upload. It even comes with example serverside code for several PHP application frameworks.
You can't upload file using AJAX , you need to use a trick consisting a 'iframe' and the web form , also some javascript.
This link may help you.
HTML
<div class="field">
<label class="w15 left" for="txtURL">Logo:</label>
<img id="logoPreview" width="150px" height="150px" src='default.jpg' />
<input class="w60" type="file" name="txtURL" id="txtURL" />
</div>
JQuery
$('#txtURL').on('change', function(){
$.ajaxFileUpload({
type : "POST",
url : "ajax/uploadImage",
dataType : "json",
fileElementId: 'txtURL',
data : {'title':'Image Uploading'},
success : function(data){
$('#logoPreview').attr('src', data['path']);
},
error : function(data, status, e){
alert(e);
}
});
});
Ajax controller:
public function uploadImage()
{
$status = "";
$msg = "";
$filename='';
$file_element_name = 'txtURL';//Name of input field
if (empty($_POST['title'])){
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error"){
$targetPath = ''.date('Y').'/'.date('m').'/';
if(!file_exists(str_replace('//','/',$targetPath))){
mkdir(str_replace('//','/',$targetPath), 0777, true);
}
$config['upload_path'] = $targetPath;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 150000;
$config['file_name']=time(); //File name you want
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($file_element_name)){
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else{
$data = $this->upload->data();
$filename = $targetPath.$data['file_name'];
}
//#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg,'path'=>$filename));
}
Add Ajaxfileupload.js
You can't upload an image directly using AJAX
The answer is in response to this:
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",

Categories