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'])) {
Related
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>
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
};
});
I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.
<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
<div class="form-group">
<label><b>Profile Image <span class="required">*</span></b></label>
<input accept="image/*" type="file" id="picture" name="picture" required>
</div>
<div class="clearfix">
<button type="submit" id="login" class="signupbtn">Sign Up</button>
</div>
</form>
I have found on another thread here on SO that I need to put this on my ajax script
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
And this is whole ajax
function submitForm()
{
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data=="registered")
{
}
}
});
return false;
}
And the server side for the picture part and the query
if(!empty($_FILES['picture']) && $_FILES['picture']['size'] >0 ){
$profilePic = $randomString. basename($_FILES['picture']['name']);
$uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
} else {
$error = "error\n";
}
}else{
$error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
$stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(":email"=>$email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
$stmt->bindParam(":picture",$profilePic);
if($stmt->execute()) {
echo "registered";
}
else { echo "Query could not execute !"; }
}
else{ echo "1"; }
}
catch(PDOException $e){
echo $e->getMessage();
}
I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.
What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])
jQuery processes the data as a string if you don't use proccessData: false. Bellow code will work just fine. Also included some comments in code
$(document).ready(function (e){
$("#login-form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "registration.php",
type: "POST",
data: new FormData(this), // Data sent to server
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){
if(data=="registered"){}
},
error: function(){}
});
}));
});
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.
So ajax code will look like
$(".signupbtn").click(function(e){
e.preventDefault();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : form,
contentType: false,
processData: false,
success : function(data){}
});
});
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/
I have a code from the tutorial and i dont know what happen's why mine doesn't work. I just follow the tutorial and the code doesn't work. I am using a codeigniter framework, please help me with these, i have no error in console also, i dont know what's happening why . Also it doesn't sends a request from ajax. Please check the code in ajax. Thanks.
ajax code:
$(function () {
var inputFile = $('input[name=file]');
var uploadURI = $('#form-upload').attr('action');
$('#upload-btn').on('click', function(event) {
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData();
formData.append("file", fileToUpload);
$.ajax({
url: uploadURI,
type: "POST",
data: formData,
processData: false,
contentData: false,
success: function(data) {
alert("Profile picture updated!");
}
});
}
});
});
from view :
<form action="<?php echo site_url("profile/profile_picture") ?>" id="form-upload">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput"><i class="glyphicon glyphicon-file fileinput-exists"></i> <span class="fileinput-filename"></span></div>
<span class="input-group-addon btn btn-default btn-file"><span class="fileinput-new"><i class="glyphicon glyphicon-paperclip"></i> Select file</span><input type="file" name="file"></span>
<i class="glyphicon glyphicon-open"></i> Upload
</div>
</form>
controller:
public function profile_picture() {
$config['upload_path'] = "./assets/uploaded_images/";
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
}
else {
echo "File cannot be uploaded";
}
}
i got this error :
File cannot be uploadedarray(1) {
["error"]=>
string(43) "<p>You did not select a file to upload.</p>"
}
OK the problem is it should be 'contentType' not 'contentData'. Here is updated JS code
$(function () {
var inputFile = $('input[name=file]');
var uploadURI = $('#form-upload').attr('action');
$('#upload-btn').on('click', function(event) {
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: uploadURI,
data: formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Profile picture updated!");
}
});
}
});
});
You can my thread that , i gave the solution for multiple images upload using ajax , its quite easy just remove the array from name of my solution , then you will get your image in controller .
here's the link of solution of mine .
getting error while uploading image via Ajax