Image is not uploading using jquery in codeigniter - php

I am trying to upload the image to the folder in codeginter using jquery. But I am not able to get what is the exact issue why the image is not getting upload and showing me message
You did not select a file to upload.
I am not able to get why the file is not selected to upload here. Her is my php code
public function add_new_book()
{
$image = $this->input->post('bookfile');
$img=$this->input->post('bookfile');
$config['upload_path'] = '/uploads';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('bookfile'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
}
And I write jquery code here
$( document ).ready(function() {
$("#btnsavebook").click(function(){
if($("#bookfileid").val() != ''){
if (typeof FormData !== 'undefined') {
var formData = new FormData($("#form-upload")[0]);
console.log("formdata:",formData)
$.ajax({
type: "POST",
url: "CreateBook/add_new_book",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success: function(result){
}
});
} }
});});
Anybody please tell me how can I achieve this process??
Thanks

Try this
View file
<html>
<head>
<title>Ajax Image Upload Using PHP and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="my_image" id="my_image" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
<h4 id='loading' >loading..</h4>
<div id="message"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "<?php echo base_url('test/hello'); ?>", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
public function __construct ()
{
parent::__construct();
}
public function index()
{
$this->load->view('test');
}
public function hello()
{
// print_r($_FILES['file']); die;
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'gif|jpg|png|jpeg'; // allowed file formats
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('my_image'))
{
echo $this->upload->display_errors(); // It will return errors if file not uploaded
}
else
{
echo "uploaded";
}
}
}
Source : https://www.formget.com/ajax-image-upload-php/

Related

file upload get null value in Codeigniter controller

i am trying to upload image using ajax in Codeigniter without form Submit my html code is
<div class="profile-img">
<img class="" src="<?php echo base_url() ?>assets/dist/img/<?php echo $adminData->image ?> " alt="User profile picture">
<div class="file btn btn-lg btn-primary">
Change Photo
<input type="file" name="profile_img" id="profile_img"/>
</div>
<span id="uploaded_image"></span>
</div>
using this code i am send ajax on change event using given code
$('#profile_img').change(function () {
var file_data = $('#profile_img')[0].files;
var form_data = new FormData();
form_data.append('profile_img',file_data);
var admin_id= <?php echo (int)$adminData->admin_id ?>;
$.ajax({
url: "<?php echo base_url(); ?>admin/upload_image",
method: "GET",
data: {admin_id: admin_id, form_data: form_data},
contentType: false,
cache: false,
processData: false,
beforeSend: function ()
{
$('#uploaded_image').html("<label class='text-success'>Uploading...</label>");
},
success: function (data)
{
$('#uploaded_image').html(data);
}
})
});
it working fine but when we have hit controller its get null value both admin_id and form_data
my actual problem here i am still to trying get value but it always given null value
my controller code is
function upload_image() {
$data['admin_id'] = $this->input->post('admin_id');
if (isset($_FILES['form_data']['name'])) {
$config1['upload_path'] = 'assets/dist/img/';
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'gif|jpg|png|jpeg';
$config1['file_name'] = $_FILES['form_data']['name'];
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
if (!$this->upload->do_upload('form_data')) {
$error = array('error' => $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$data['image'] = $fileData['file_name'];
}
}
$this->admin_mod->update_image($data);
}
can anyone suggest me where am i wrong.
You're passing a FileList to FormData.append you have to pass a File. You can pass the first file in the list like in an array.
var file_data = $('#profile_img')[0].files[0];
Also your file is sent as profile_img you're trying to read it as form_data
if (isset($_FILES['profile_img']['name'])) {

unable to upload file in codeigniter using AJAX

I'm trying to upload the file in CodeIgniter using Ajax but the problem is the file is uploading in the database but unable to do it without loading the page. Every time I upload a file it uploading successfully but navigating to its controller address with JSON code. I just want to upload the file without refreshing page.
View FILE
<?php echo form_open_multipart('maker/Checkout/docs', array('id'=>'upload_file')); ?>
<div class="form-group">
<label for="userfile">Upload existing CV</label>
<input class="form-control" type="file" name="userfile" id="userfile" size="20" />
</div>
<div class="form-group">
<button class="btn btn-info" type="submit">Upload</button>
</div>
<?php echo form_close() ?>
Ajax Code
<script>
$(function() {
$('#upload_file').unbind('submit').bind('submit', function() {
e.preventDefault();
var form = $(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
</script>
Controller
public function docs() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error")
{
$config['upload_path'] = dirname($_SERVER["SCRIPT_FILENAME"])."/assets/img/posts";
$config['upload_url'] = base_url()."/assets/img/posts";
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|docx|docs|txt|xml';
$config['max_height'] = 102048;
$config['max_width'] = 102048;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$file_id = $this->Checkout_model->newcheckout($data['file_name']);
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
I just want to upload the file without refreshing the page. Currently, it's uploading the file but after upload its navigating to the controller address.
The reason why you're navigating to controller is because your call to preventDefault is from a non existent identifier e causing an error, you can remove it since you have return false later or just define the e.
Now when you're trying to upload a file with ajax you use a FormData object
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {//<-- e defined here
e.preventDefault();
var form = $(this);
var data = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: data,
processData: false,
contentType: false,
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
Slightly different variation of solution that worked for me is given below:
<script type="text/javascript">
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {
e.preventDefault();
var file = document.getElementById('userfile').files[0];
if(file==undefined){
return false;
}
var formData = false;
if (window.FormData) {
formData = new FormData();
formData.append("userfile", file);
}
var form = $(this);
if(formData!==false){
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
processData: false,
secureuri: false,
contentType: false,
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
}
return false;
});
});
</script>

How to upload file and insert data with php jquery ajax

I cannot send via ajax to php file upload and data with ajax. This my code just send file upload. data not send to my php code. I create form and the function send on click using ajax to post on php. I'm using codeigniter
This my form:
<form action="<?php echo site_url('home/send_chat');?>" method="post" enctype="multipart/form-data">
<input name="message" id="message" type="text" class="form-control input-sm" />
<input type="file" id="file" name="file" />
<br />
<span class="input-group btn">
<button type="submit" class="btn btn-info btn-sm" id="submit">Enkripsi</button>
</span>
</form>
This javascript to send post on php using ajax:
$('#submit').on('click', function(){
var message = $('#message').val();
var fd = new FormData(this);
fd.append('file',$('#file')[0].files[0]);
$.ajax({
method:"POST",
url:"<?php echo site_url('home/send_chat');?>",
data: {fd,message:message},
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
I'm already try using $_POST['message']; and $this->input->post("message"); its not work both
This php to proces code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function send_chat()
{
$name = $_FILES['file']['name'];
$error = $_FILES['file']['error'];
$size = $_FILES['file']['size'];
// $message = $_POST['message'];
$message = $this->input->post("message");
$user = $this->session->userdata('username');
$iduser = $this->session->userdata('userID');
$insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$userid','$name')";
$this->db->query($insert);
}
}
In database i'm just send name file upload.user, message, and iduser its not send.
i think your problem may be in ajax code
since you are using formData object . try append the message variable with it
$('#submit').on('click', function(){
var fd = new FormData(this);
fd.append('file',$('#file')[0].files[0]);
fd.append('message ',$('#message').val());
$.ajax({
method:"POST",
url:"<?php echo site_url('home/send_chat');?>",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
try to make ajax code like this.
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({
type : "POST",
url : "<?=base_url()?>home/send_chat",
data : data,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
and your controller make like this it's working code for me
class Home extends CI_Controller {
function singleImageUpload($upload_name,$folder,$extension,$bnr,$filename)
{
if($folder == '')
{
$config['upload_path'] = 'images/agent';
}
else
{
$config['upload_path'] = 'upload/'.$folder."/";
}
$config['allowed_types'] = '*';
if($bnr == 2)
{
$config['max_width'] = '3000';
$config['max_height'] = '3000';
}
elseif ($bnr == 1)
{}
// $config['file_name'] = $user_name.date('YmdHis').".".$extension;
$config['file_name'] = $filename;
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($upload_name))
{
$arrayRetutn['upload'] = 'False';
$arrayRetutn['error'] = $this->upload->display_errors();
}
else
{
$arrayRetutn['upload'] = 'True';
$arrayRetutn['data'] = $this->upload->data();
}
//echo '<pre>';print_r($arrayRetutn);echo '</pre>'; die;
return $arrayRetutn;
}
public function send_chat()
{
$user = $this->input->post("user");
$message = $this->input->post("message");
$iduser = $this->input->post("iduser");
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
{
$image_name = explode(".",$_FILES['file']['name']);
$imgData = $this->singleImageUpload('file','your folder name',$image_name[1],'2',$_FILES['file']['name']);
if($imgData['upload']=='True')
{
$name = $imgData['data']['file_name'];
}
}
$insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$iduser','$name')";
$this->db->query($insert);
}
}
I think the point #kunal was making was that you should not add potentially sensitive data as hidden inputs ( anyone can change it ) but should reference the values held in those fields directly within your class before adding to the db. In addition using embedded variables opens your app to sql injection so use a prepared statement.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function send_chat(){
$name = $_FILES['file']['name'];
$error = $_FILES['file']['error'];
$size = $_FILES['file']['size'];
$user = $this->session->userdata('username');
$iduser = $this->session->userdata('userID');
$message = $this->input->post("message");
$sql="insert into `chat` ( `user`, `message`, `id_user` ,`fileupload` ) values (?,?,?,?)";
$stmt=$this->db->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssss',$user,$message,$userid,$name);
$stmt->execute();
}
}
}
I played around with your original javascript/jQuery code but could not get the function to work ( I don't use jQuery so I was guessing ) but using regular, vanilla javascript you can do it like this ~ the portion of php code at the top is not really relevant as you would be sending the ajax request to home/send_chat
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* send some sort of response... */
echo json_encode( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>xhr upload - no jquery</title>
<script>
document.addEventListener('DOMContentLoaded',function(){
var callback=function( data ){
alert( data )
}
document.getElementById('submit').onclick=function(e){
e.preventDefault();
var url='<?php echo site_url('home/send_chat');?>';
var _file=document.querySelector('input[type="file"]');
var _form=document.querySelector('form[id="usr-upload"]');
var xhr = new XMLHttpRequest();
var fd=new FormData( _form );
fd.append('file', _file.files[0]);
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
};
xhr.onerror=function(err){
alert(err);
};
xhr.open('POST',url,true);
xhr.send( fd );
};
},false );
</script>
</head>
<body>
<form id='usr-upload' method='post' enctype='multipart/form-data'>
<input name='message' type='text' />
<input type='file' name='usrfile' />
<br />
<span class='input-group btn'>
<input type='button' value='Enkripsi' id='submit' />
</span>
</form>
</body>
</html>
Submit all the data with or without file using ajax
<form method="post" action="" enctype="multipart/form-data" id="form"/>
// your own input fields
</form>
$("#form").submit(function (event) {
event.preventDefault();
//tinyMCE.triggerSave();
$.ajax({
url: "<?php echo base_url('your_own_controller/your_own_method'); ?>",
type: "post",
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
async: false,
beforeSend: function () {}, //if you like to do something before submit
complete: function () {}, //if you like to do something before submit
success: function (response) {
//check response and do some your own stuff
};
});

How to debug a non-working response from AJAX in CodeIgniter?

I want to upload photo with jquery-ajax in CodeIgniter. First I want to pass file to my controller for just check my AJAX call properly working or not.
My code is not posting anything to my controller. I posting my code here, please show me my fault
Here is my code
jQuery and my input of my view is here (profile_view.php)
<script type="text/javascript">
$(document).ready(function() {
$("#file1").on("change", (function() {
$("#showimage").fadeIn("slow").html('');
$("#showimage").fadeIn("slow").html('Plaese Wait...');
alert('hello');
$("#frm1").ajaxForm({
target: '#showimage',
success: function(response) {
alert(response);
},
error: function(err) {
alert(err);
}
}).submit();
}));
</script>
My input code is here
<div id="photoframe">
<form name='frm1' id="frm12" enctype="multipart/form-data" method="post" action="upload_photo">
<input type="file" name="file1" id="file1" style="visibility:hidden" />
</form>
<a style="color:white"><i class="fa fa-edit" id="img1">Edit Photo</i></a>
<div id="showimage" name='showimage'>
</div>
</div>
My controller is Here (upload_photo.php)
class Upload_photo extends CI_Controller {
function __construct() {
parent::__construct();
$this - > load - > helper(array('form', 'url'));
}
public
function index() {
$config['upload_path'] = '/user';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
if (isset($_POST['frm1'])) {
echo 'Image Uploaded';
echo "post".$_FILE['frm1'];
} else {
echo 'Image Upload Failed';
}
}
}
My output is : Image Upload Failed
I think there is problem with your request, You have not passed any data with that request, You can use following data method to pass data with ajax:-
$.ajax({
url: "post.php",
data: {
id: 123
},
type: "GET",
dataType : "json",
success: function( json ) {
// Do your code here for success
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
And you can not send image file with these AJAX request.
Please change your PHP code also, something like following :-
if (isset($_FILES['frm1'])) {
// Do your upload code here
}
else
{
echo 'Image Upload Failed';
}
This is the ajax call for non processed data (in your case upload images):
var form = $('frm12');
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url: formAction,
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
dataType: "json",
type : 'POST',
resetForm: true,
})
.done(function(data) {
//returned response
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
Please note the "processData: false", this is needed to tel ajax to not act as a standard data transfer.
"By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false." from http://api.jquery.com/jquery.ajax/. You can find here explaination about the jquery.ajax settings.
Is worth to mention that if you want to make some checks before sending the data to the server (and I reccoment this) you can also use the "beforeSend: beforeSubmit," setting where "beforeSubmt" is a function that you can implement where you will make all the needed checks (e.g. allowed file type, allowed file size and more...). If something fails than the data will not be uploaded.

Why, when uploading files via Ajax, is CodeIgniter throwing a "no file uploaded" error?

All I'm trying to do is upload files using ajax to my CodeIgniter based website. But for some reason CodeIgniter keeps giving the "no file uploaded" error. How can I resolve this?
Here is the JavaScript:
<script type="text/javascript">
function updatebgimage()
{
regexp = /^[^[\]]+/;
var imgfile = document.getElementById("imagetoresize");
var fileInputName = regexp.exec( imgfile['name'] );
formdata = new FormData();
formdata.append("imagetoresize",imgfile.files[0]);
$.ajax({
url: "<?php echo site_url('uploadbgimage'); ?>",
type: "POST",
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
alert(data.message);
}
});
}
</script>
Here is the CodeIgniter controller being called:
public function uploadbgimage()
{
$config['upload_path'] = './images/stores/'.$memberid.'/';
$config['file_name'] = 'main_bg_image.jpg';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = true;
$this->load->library('upload', $config);
$data = array();
if (! $this->upload->do_upload("bgimage"))
{
$data['result'] = 'fail';
$data['message'] = $this->upload->display_errors();
}
else
{
$data['result'] = 'success';
$data['message'] = 'file was uploaded fine';
}
echo json_encode($data);
}
Here is the HTML:
<form method="post" enctype="multipart/form-data">
<input type="file" id="imagetoresize" name="imagetoresize" value="" class="field1" />
<input type="button" onclick="updatebgimage()" value="UploadBGImage" />
</form>
Shouldn't it be:
formdata.append("imagetoresize",imgfile.file);
See https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

Categories