Upload Image to Database using Ajax and Codeigniter - php

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');
}
});
});
}

Related

Form Validation and inserting data, with php and Codeigniter 3.1.11

Here I am trying to make a form which enables admin to add a new company , i need to implement the form validation and after that insert data to table (company_details),here is what i have done, using codeigniter and ajax, I am not sure if there is other simple ways to do this process without using ajax , so if there is i would appreciate you help me. here is my code but now when i press create button notting actually happens, and i get
"error :Failed to load resource: the server responded with a status of 500 (Internal Server Error). company:1"
Company.php Controller
<?php
class Company extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
$this->load->model('company_model');
}
function index()
{
$data['company'] = $this->company_model->getCompanyDetails();
$this->load->view('admin/company', $data);
}
function validation()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('Cname' , 'Company Name' , 'required');
$this->form_validation->set_rules('shname' , 'Short Name' , 'required');
$this->form_validation->set_rules('regNo' , 'Registration No' , 'required|valid_regNo');
if($this->form_validation->run())
{
$this->company_model->create();
$array = array(
'succsee' => '<div class="alert alert success">Your Company Added Sucessfully</div>'
);
redirect('admin/company/');
}
else
{
$array = array(
'error' => true,
'Cname_error' => form_error('Cname'),
'shname_error' => form_error('shname'),
'regNo_error' => form_error('regNo'),
);
}
echo json_encode($array);
}
}
company.php view
<div class="companyAdd" style="display: none;">
<h2 class="heading">Add Company</h2>
<span action="<?php echo site_url('admin/staff/validate');?>" id="success_message"></span>
<form method="post" id="AddCompanyForm">
<div class="row">
<div class="form-group col-md-4">
<label for="email">Company Name</label>
<input type="text" class="form-control" id="Cname" placeholder="Name" name="Cname">
<span id="Cname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Short Name</label>
<input type="text" class="form-control" id="shname" placeholder="Short Name" name="shname">
<span id="shname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Registration No</label>
<input type="text" class="form-control" id="regNo" placeholder="01234567" name="regNo">
<span id="regNo_error" class="text-danger"></span>
</div>
<div class="col-md-12">
<div class="btn-section float-right">
<button class="btn btn-outline-primary" type="submit"><i class="fa fa-plus-circle" aria-hidden="true" id="Ccreat"></i> Create</button>
<button class="btn btn-danger float-right" id="cancelCompany" type="button" onClick="window.location.href=admin/company"><i class="fa fa-plus-circle" aria-hidden="true"></i> Cancel</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
This is my script tag in company.php view
<script>
$(document).ready(function(){
$('#AddCompanyForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"<?php echo site_base();?>admin/company/validation",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#Ccreat').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.error)
{
if(data.Cname_error != '')
{
$('#Cname_error').html(data.Cname_error);
}
else
{
$('#Cname_error').html('');
}
if(data.shname_error != '')
{
$('#shname_error').html(data.shname_error);
}
else
{
$('#shname_error').html('');
}
if(data.regNo_error != '')
{
$('#regNo_error').html(data.regNo_error);
}
else
{
$('#regNo_error').html('');
}
}
if (data.success)
{
$('#success_message').html(data.success);
$('#Cname_error').html('');
$('#shname_error').html('');
$('#regNo_error').html('');
$('#AddCompanyForm')[0].reset();
}
$('#Ccreat').attr('disabled',false);
}
})
});
});
</script>
And here is Company_model.php
<?php
class Company_model extends CI_Model
{
//table name: company_details
function getCompanyDetails()
{
return $this->db->get('company_details')->result();
}
function create()
{
$arr['company_name'] = $this->input->post('Cname');
$arr['short_name'] = $this->input->post('shname');
$arr['registration_no'] = $this->input->post('regNo');
$this->db->insert('company_details',$arr);
}
}
This is my first time working with codeigniter and ajax , i would appreciate if someone can help me to solve it.

Laravel, how to show forms error with ajax submit?

I use ajax to submit a form without having to reload the page after, but I really don't know how to get the forms errors, especially for the required fields.
Here is my form, it's a simple form with two datepicker:
<form>
<div class="form-group row">
<label for="date_debut" class="col-md-4 col-form-label text-md-right">Date de début</label>
<div class="col-md-6">
<input type="text" id="date_debut" name="date_debut" class="datepicker-here form-control" data-timepicker="true" data-language='fr' placeholder="Choisir une date" />
</div>
</div>
<div class="form-group row">
<label for="date_fin" class="col-md-4 col-form-label text-md-right">Date de fin</label>
<div class="col-md-6">
<input type="text" id="date_fin" name="date_fin" class="datepicker-here form-control" data-timepicker="true" data-language='fr' placeholder="Choisir une date" />
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button id="ajoutDispoButton" onclick="myfunction()" type="button" class="btn btn-primary">
Ajouter
</button>
</div>
</div>
<input type="hidden" id="user_id" name="user_id" class="form-control" value="{{$user->id}}" required>
</form>
And here is my Ajax call :
function myfunction(param){
var date_debut = $('#date_debut').val();
console.log(date_debut);
var date_fin = $('#date_fin').val();
var user_id = $('#user_id').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route('createDispo') }}',
type: 'POST',
dataType: "json",
data: {
user_id: user_id,
date_debut: date_debut,
date_fin: date_fin,
},
success: function (data) {
$("#centralModalSuccess").modal();
$("#date_fin").val("");
$("#date_debut").val("");
},
error: function (data) {
var errors = data.responseJSON;
console.log(errors);
}
});
}
And here my controller :
public function createDispo(Request $request){
$user = User::find($request->user_id);
$disponibilite = new Disponibilite();
$disponibilite->date_debut = Carbon::createFromFormat('d/m/Y H:i',$request->date_debut);
$disponibilite->date_fin = Carbon::createFromFormat('d/m/Y H:i',$request->date_fin);
$user->disponibilites()->save($disponibilite);
return response()->json(['ok' => 'ok']); // Return OK to user's browser
}
I think this is not the right way to proceed, but this work. The problem is that I want to handle the validations errors, my fields are required but I can send the ajax call even if they are empty.
Anyone know how to do that?
you can make form validation with jquery instead of laravel validation
Look at this question : A simple jQuery form validation script
Add validation in controller function
public function createDispo(Request $request){
$request->validate([
'date_debut' => 'required',
'date_fin' => 'required',
]);
// your code
}
and display the errors in html.

Getting a null value in my input file type field

I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});

Error Uploading File with AJAX in codeigniter

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();
}

Codeigniter save ajax response

I want to save the ajax response I get into my database. The problem is that my ajax function doesn't allow my to put a insert query. When I Insert the insert query, my response doesn't work anymore and vice versa.
where ajax file is
public function submit() {
$data = array(
'user_id' => '1',
'swipedpicture' => $this->input->post()
);
$this->db->insert('tbl_results', $data);
print json_encode($data);
}
Ajax Jquery
var pic = $(this).find('input[name="inputcountry"]').attr('value');
jQuery.ajax({
type: "POST",
url: window.location.origin +"/swipr/index.php/preferences/submit",
dataType: 'json',
data: {swipedpic: pic},
success: function(res) {
if (res) {
console.log(res.swipedpicture);
}
}
});
Your javascript is setting a data element for posting that the submit function is not using.
The submit function should look like this.
$data = array(
'user_id' => '1',
'swipedpicture' => $this->security->xss_clean($this->input->post('swipedpicture'))
);
$this->db->insert('tbl_results', $data);
$response_array['status'] = 'success';
echo json_encode($response_array);
The javascript should look more like this. I used an form id of form1 and a form element of swipedpicture.
$('#form1').submit(function(e){
e.preventDefault();
$.ajax({
url: 'example_answer_submit',
type: 'POST',
data: $('#form1').serialize(),
success: function (msg) {
if (!msg) {
console.log('error');
} else {
console.log('success');
}
}
});
return false;
});
The form I used.
<h1 class="page-header text-center">Test Form</h1>
<form id="form1" class="form-horizontal" role="form" method="post" action="">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Swiped Picture</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="swipedpicture" name="swipedpicture" placeholder="Pic" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>

Categories