Error Uploading File with AJAX in codeigniter - php

I am making an admin panel in codeigniter. I have a table games. It has an image inside it. I want to upload that image using ajax. But for some reason, the image is not being uploaded and error occurs no file selected.
Controller
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update() {
$this->_validate();
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id')
);
$this->game->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
HTML
<div class="container">
<h1 style="font-size:20pt">Games</h1>
<h3>Game Data</h3>
<br />
<button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
<button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
Javascript
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function () {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('game/ajax_list') ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, -3], //last column
"orderable": false, //set not orderable
},
],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_game()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
}
function edit_game(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data)
{
$('[name="id"]').val(data.id);
$('[name="title"]').val(data.title);
$('[name="iframe"]').val(data.iframe);
$('[name="status"]').val(data.status);
$('[name="category_id"]').val(data.category_id);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
}
});
}
function delete_game(id)
{
if (confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
type: "POST",
dataType: "JSON",
success: function (data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
</script>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Game Form</h3>
</div>
<div class="modal-body form">
<?php
$attributes = array(
'id' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart('#', $attributes);
?>
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Title" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Iframe</label>
<div class="col-md-9">
<textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select name="category_id" class="form-control">
<option value="">--Select Category--</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<?php echo form_upload(['name' => 'image']); ?>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Status</label>
<div class="col-md-9">
<select name="status" class="form-control">
<option value="">--Select Status--</option>
<option value="0">Inactive</option>
<option value="1">Active</option>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->

Noticed several required condition you missed in code
First in your ajax_add method
if ($this->upload->do_upload()) this should contain image field name like
if ($this->upload->do_upload('image')){// as your file upload field name is "image"
}
Then for ajax upload your client side code some params are missing
contentType: false,
processData: false,
so your ajax method should (in save method) looks like
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
contentType: false,
processData: false
.....
processData this is important when file upload via ajax

In addition to the suggestions from Rejoanul, you may want to check that you are not uploading a file that is too large.
Apparently if the file you are attempting to upload is larger than the maxsize, the FILES variable will be empty.
https://stackoverflow.com/a/21633123/2153218

Try to change This line in your controller
$img = "img"; // input name="img"
$this->upload->do_upload($img);

Try this
$config = array( 'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
'overwrite' => TRUE, );
get_instance()->load->library('upload', $this->config);
if($this->upload->do_upload('image')) {
echo "file upload success";
} else {
echo $this->upload->display_errors();
}

Related

Laravel update mysql table return empty data

I am developing an application where i display/edit/delete data from Mysql table using laravel and datatables. I get this error when trying to add or edit data and update it in Mysql table:
Here is code:
<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Datatables Server Side Processing in Laravel</h3>
<br />
<div align="right">
<button type="button" name="add" id="add_data" class="btn btn-success btn-sm">Add</button>
</div>
<br />
<table id="student_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th><button type="button" name="bulk_delete" id="bulk_delete" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-remove"></i></button></th>
</tr>
</thead>
</table>
</div>
<div id="studentModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="student_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="student_id" id="student_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
$('#add_data').click(function(){
$('#studentModal').modal('show');
$('#student_form')[0].reset();
$('#form_output').html('');
$('#button_action').val('insert');
$('#action').val('Add');
$('.modal-title').text('Add Data');
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#student_id').val(id);
$('#studentModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.removedata')}}",
mehtod:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
})
}
else
{
return false;
}
});
$(document).on('click', '#bulk_delete', function(){
var id = [];
if(confirm("Are you sure you want to Delete this data?"))
{
$('.student_checkbox:checked').each(function(){
id.push($(this).val());
});
if(id.length > 0)
{
$.ajax({
url:"{{ route('ajaxdata.massremove')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
});
}
else
{
alert("Please select atleast one checkbox");
}
}
});
});
</script>
</body>
</html>
Controller:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Student;
use Yajra\DataTables\DataTables;
class AjaxdataController extends Controller
{
function index()
{
return view('student.ajaxdata');
//http://127.0.0:8000/ajaxdata
}
function getdata()
{
$students = Student::select('id', 'first_name', 'last_name');
return DataTables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
function postdata(Request $request)
{
$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == "insert")
{
$student = new Student([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$student->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
if($request->get('button_action') == 'update')
{
$student = Student::find($request->get('student_id'));
$student->first_name = $request->get('first_name');
$student->last_name = $request->get('last_name');
$student->save();
$success_output = '<div class="alert alert-success">Data Updated</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
function fetchdata(Request $request)
{
$id = $request->input('id');
$student = Student::find($id);
$output = array(
'first_name' => $student->first_name,
'last_name' => $student->last_name
);
echo json_encode($output);
}
function removedata(Request $request)
{
$student = Student::find($request->input('id'));
if($student->delete())
{
echo 'Data Deleted';
}
}
function massremove(Request $request)
{
$student_id_array = $request->input('id');
$student = Student::whereIn('id', $student_id_array);
if($student->delete())
{
echo 'Data Deleted';
}
}
}
web.php:
Route::get('ajaxdata', 'AjaxdataController#index')->name('ajaxdata');
Route::get('ajaxdata/getdata', 'AjaxdataController#getdata')->name('ajaxdata.getdata');
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
Route::get('ajaxdata/fetchdata', 'AjaxdataController#fetchdata')->name('ajaxdata.fetchdata');
Route::get('ajaxdata/removedata', 'AjaxdataController#removedata')->name('ajaxdata.removedata');
Route::get('ajaxdata/massremove', 'AjaxdataController#massremove')->name('ajaxdata.massremove');
Only delete is working. Also i want to use select-checkbox attribute of datatable but it doesn't work, like this one link for the line color on selection but with multiple selections.
Thanks to #Alaksandar Jesus Gene i solved this issue by changing the post request by a get request for the postdata function inside web.php file and inside the view related script code. Now that it works my second concern still unresolved.
Can u try this
$(document).on('click', '.edit', function () {
data = {};
data.id = $(this).attr("id");
data.first_name = "User"; //$('#first_name').val();
data.last_name = "hello"; //$('#last_name').val();
data.student_id = $(this).attr("id");
data.action = 'Edit';
data.button_action = 'update';
$('#form_output').html('');
$.ajax({
url: "{{route('ajaxdata.fetchdata')}}",
method: 'post',
data: data,
dataType: 'json',
success: function (data) {
// $('#studentModal').modal('show');
// $('.modal-title').text('Edit Data');
console.log("data", data);
},
error: function(err){
console.log("err", err);
}
})
});
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
The router expects post request but you are sending GET request. Please change the method as shown

Upload Image to Database using Ajax and Codeigniter

I have a CRUD with ajax working , but i want to implement a file upload to it.
Everything works fine except the image upload , the image is the only thing that is not saving on database and folder , all the other data are saving.
This is my CRUD Controller(just the add part) where I've implemented the upload code (dados)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('dados_model');
$this->load->database();
}
public function index()
{
$data['dados']=$this->dados_model->get_all_dados();
$this->load->view('dados_view',$data);
}
public function dados_add()
{
$config = array(
'upload_path' => "./assets/uploads",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
);
$this->load->library('upload',$config);
$this->upload->do_upload('userfile');
$data2=array('upload_data' => $this->upload->data());
$data = array(
'Name' => $this->input->post('Name'),
'City' => $this->input->post('City'),
'address' => $this->input->post('address'),
'lastname' => $this->input->post('lastname'),
'Image' =>$data2['upload_data']['file_name']
);
$this->dados_model->dados_add($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->dados_model->get_by_id($id);
echo json_encode($data);
}
And this is my Model, I use it to store the data on the database(dados_model)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados_model extends CI_Model
{
var $table = 'dados';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_dados()
{
$this->db->from('dados');
$query=$this->db->get();
return $query->result();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('ID',$id);
$query = $this->db->get();
return $query->row();
}
public function dados_add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
This is my Ajax code to save
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal
title
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data:$('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
and this is my Modal Form to save
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">dados Form</h3>
</div>
<div class="modal-body form">
<form action="#" method="post" enctype="multipart/form-data" id="form"
class="form-horizontal">
<input type="hidden" value="" name="ID"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Name</label>
<div class="col-md-9">
<input name="Name" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input name="City" placeholder="City" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<input name="Address" placeholder=""
class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
<input type ="submit" name="submit" value="Salvar" id="btnSave "
onclick="save()" class="btn btn-primary" />
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
</body>
</html>
First, try adding a '/' to the end of 'upload_path' => "./assets/uploads" in your code. This way you have a complete path for the image to go to.
Also, just so your aware, uploading an image like this will save the image on your server in the path provided. This means you need to store the file name in the database.So Make sure that 'Image' =>$data2['upload_data']['file_name'] actually has the correct file name so that when you query that file name from the db you can then find it at ./assets/uploads/filename on your server.
Additionally,
What do you get if you var_dump($data2['upload_data']['file_name'])?
What do you get if you var_dump($this->upload->display_errors()) after calling do_upload?
after searching some ajax codes, this is what worked for me
I changed my ajax function save to this
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
$('#form').submit(function(e)
{
$.ajax({
url : url,
type: "POST",
data: new FormData(this),
dataType: "JSON",
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
});
}

Ajax image upload error in Codeigniter 3

Hello I'm using Codeigniter 3 and jQuery ajax.
I'm using the built in upload library...
I want to upload image on my server, but always get this error message:
You did not select a file to upload.
Here is my code
View
<?php echo form_open_multipart('settings/uploadprofilephoto', array('id' => 'upload-avatar-form'));?>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload profile photo</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="row">
<div class="form-group col-md-6">
<input type="file" name="profilephoto" id="profile-photo" class="form-control">
</div>
<div class="form-group col-md-6">
<button type="submit" id="upload" class="btn btn-success">Upload</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<?php echo form_close();?>
Controller
public function uploadProfilePhoto(){
$config = array(
'upload_path' => base_url() . 'uploads/test',
'allowed_types' => 'jpg|jpeg|gif|png',
'min_height' => 480,
'min_width' => 640,
'remove_spaces' => true,
);
$this->load->library('upload', $config);
if($this->upload->do_upload("profilephoto")){
$data = array(
'status' => true,
'messages' => 'Uploaded'
);
echo json_decode($data);
}else{
$data = array(
'status' => false,
'messages' => $this->upload->display_errors()
);
echo json_encode($data);
}
}
ajax
/*
Upload profile photo
*/
$("#upload-avatar-form").submit(function(event){
$.post(base_url + "settings/uploadprofilephoto" , $(this).serialize(), function(data){
console.log(data);
//alert("ok");
});
event.preventDefault();
});
Where am I wrong?
serialize() will not pass image within it. It does not work with multipart formdata.
Instead use like this:
var formData = new FormData(this);
Pass this formData variable instead of $(this).serialize()
Try this
$('#button_name').on('click', function(event) {
event.preventDefault();
$.ajax({
url: "<?php echo base_url('settings/uploadprofilephoto');?>",
type: 'post',
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(json) {
// Success Stuff
},
});
});
On the view part
<button type="button" id="button_name">Upload</button>
You have to try this
$('#logo_form').on('submit',function(form){
form.preventDefault();
var me = $(this);
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: me.attr('action'), // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$("#logo_form")[0].reset();
$('#logo_success').html(response); // display success response from the server
window.setTimeout(function(){location.reload()},1000);
},
error: function (response) {
$('#error').html(response); // display error response from the server
}
});
});
Please check below mentioned solution, This will help you to send file with input data.
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $('#my_form input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var inputs = $('#my_form input[type="text"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("id");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="file_1" id="file_1" data-filename="image.jpg"><br />
<input type="text" name="check1" id="check1"/><br />
<input type="text" name="check2" id="check2"/><br />
<input type="text" name="check3" id="check3"/><br />
<button>Submit</button>
</form>
Let me know if it not works.

how to pass the two file value in next page through AJAX while adding muliple image in single form field

Here i have two form fields(file upload),first user select the logo and select one banner image means value is getting in next page (home.php).suppose user select one logo and select multiple banner image means i can not get the value in next page (home.php).how can do this ?
<script>
var i=0;
$(document).on("click",".add_banner",function() {
i++;
var htmlText = '';
htmlText += '<div class="form-group"><label class="col-md-3 control-label">Project Banners</label><div class="col-md-6"><div class="fileupload fileupload-new" data-provides="fileupload"><div class="input-append"><div class="uneditable-input"><i class="fa fa-file fileupload-exists"></i><span class="fileupload-preview"></span></div><span class="btn btn-default btn-file"><span class="fileupload-exists">Change</span><span class="fileupload-new">Select file</span>';
htmlText +='<input type="file" name="banners[]" id="banners' + i +'">';
htmlText += '</span><span style="margin-left:10px"><button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>Remove</div></div></div></div>';
$('#add_banner_append').append(htmlText);
});
</script>
<script>
$(document).ready(function(){
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"php/home.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
});
// Shorthand for $( document ).ready()
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="form-horizontal form-bordered" method="POST" id="empForm">
<div class="form-group">
<label class="col-md-3 control-label">Project Logo</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="logo" name="logo" required="" data-msg-required="File" value="" aria-required="true">
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Project Banners</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="banners" name="banners[]" required="" data-msg-required="File" value="" aria-required="true">
</span><span style="margin-left:10px">
<button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>
</div>
</div>
</div>
</div>
<div id="add_banner_append"></div>
<div class="form-group">
<div class="col-md-3">
</div>
<div class="col-md-6">
<input type="button" class="btn btn-primary btn-block" id="btn-submit" name="submit" value="SUBMIT">
</div>
</div>
</form
$postedBanners = array();
/* foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
} */
$uploads_dir = '/banners';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = $_FILES["banners"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
You are missing enctype in both html form and ajax calling. You should add enctype in form like as <form class="form-horizontal form-bordered" method="post" id="empForm" enctype="multipart/form-data">.
Aslo add enctype in ajax calling -
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"test.php",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
I have added enctype: 'multipart/form-data' in ajax calling.
At server end you need to get all multiple added banner image as following -
if(!empty($_FILES['banners']['name'])){
$postedBanners = array();
foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
}
echo '<pre>';
print_r($postedBanners);
}
I will return output as following -
Array
(
[0] => Array
(
[name] => preview.png
[type] => image/png
[tmp_name] => /private/var/tmp/php9Fyir9
[error] => 0
)
)
For Upload banner images in a folder.
$uploads_dir = '/uploads';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["banners"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}

im not able to call my ajax request in new added div in angular js

i have a three dropdowns like country,state,city it's using ajax reuest.
then i add new dropdowns div using my buttion , myfirst dropdown div's data passed and displayed and it's work fine, but others div's dropdown data not passed and not display and ajax request can't send .
it's my ajax request
<script>
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
function getcitydetails(id)
{
$.ajax({
type: "POST",
url: 'ajax_get_size/'+id,
data: id='st_id',
success: function(data){
$('#old_city').html(data);
},
});
}
it's my angular js code
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
and its my html
<div class="content-wrapper" ng-app="shanidkvApp">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add Challan Details
<i class="fa fa-list"></i> challan Details List
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row"> <div class="col-md-12 display_alert"></div></div>
<div class="row">
<div class="col-md-6">
<div class="box box-primary" ng-app="angularjs-starter" ng-controller="MainCtrl">
<div class="box-body table-responsive">
<form action="insert" method="post" data-parsley-validate novalidate enctype="multipart/form-data">
<div data-ng-repeat="choice in choices">
<div class="form-group">
<label for="form-address">Model Name</label>
<select name="country_details" class="form-control countries" id="country_details" onChange="getstatedetails(this.value)">
<option value="" selected="selected" >Select Model</option>
<?php foreach($groups as $count): ?>
<option value="<?php echo $count->model_id; ?>"><?php echo $count->model_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="form-address">Finish Name</label>
<select name="select_state" class="form-control countries" id="old_state" onChange="getcitydetails(this.value)">
<option selected="selected">Select Finish</option>
</select>
</div>
<div class="form-group">
<label for="form-address">Size</label>
<select name="selectcity" class="form-control countries" id="old_city" >
<option selected="selected">Select Size</option>
</select>
</div>
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice()">Remove</div>
</div>
<div class="btn btn-primary" ng-click="addNewChoice()">Add fields</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- /.content -->
data in ajax should be in object form
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
pls try
$.ajax({
...
data: { id: 'cat_id' }
})
Stop using JQuery and AngularJS together.
If you want your data, use AngularJS too.
For instance,
app.factory('requestFactory', function($q, $http) {
var ret = {
getStateDetails: getStateDetails,
getCityDetails: getCityDetails
};
return ret;
function getStateDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_finish/' + id, {id: 'cat_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
function getCityDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_size/' + id, {id: 'st_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
});
Then, load your data in your controller, and use the two-way binding to display it.

Categories