Upload image without form action using dropzone in codeigniter - codeigniter

Upload image without form action using dropzone in CodeIgniter. I need to upload an image without the form action in dropzone. that means, there are one form, dropzone image and other fields are in the form. First when we selecting an image, automatically upload the image and save in the database. And add other fields then submit the form action.

you can Upload image using AJAX with button but a button must be under the form tag with id
View
<form action="<?php echo SURL; ?>admin/registered_students/" id="file_completion_form" class="form-horizontal" method="post" enctype="multipart/form-data">
<td>
<input type="file" data-validation="" style="display: inline" name="undertaking" id="undertaking" value="" placeholder="" multiple="">
</td>
<td>
<input type="hidden" id="student_id" name="student_id" value="<?=$student_id;?>">
<button type="button" class="btn btn-info chk2" id="upload_undertaking">
<i class="fa fa-upload"></i>
</button>
</td>
<td>
<span class="alert" style="display: none" id="msg">Updated</span>
</td>
<td id="download_undertaking">
<a href="<?php echo SURL.'file/download/'.$files[0]['undertaking'];?>">
<button type="button" class="btn btn-info chk2" id=""><i class="fa fa-download"></i></button>
</a>
</td>
</form>
JS
$('#upload_undertaking').click(function(e)
{
e.preventDefault();
var data = new FormData();
var form_data = $('#file_completion_form').serializeArray();
$.each(form_data, function (key, input)
{
data.append(input.name, input.value);
});
//input quatation
var quotation_wip = $('input[name="undertaking"]')[0].files;
if(quotation_wip.length>0)
{
for (var i = 0; i < quotation_wip.length; i++)
{
data.append("undertaking[]", quotation_wip[i]);
}
}
else
{
return 0;
exit;
}
data.append('key', 'value');
var student_id = $('#student_id').val();
$.ajax(
{
url:URL+'file_completion/'+student_id,
type:'POST',
data:data,
cache:false,
contentType: false,
processData: false,
success:function(data)
{
if(data==2)
{
window.location.href=URL+'index/'+student_id;
}
else
{
var obj = jQuery.parseJSON(data);
// alert( obj.undertaking );
$("#undertaking span").html(obj.undertaking);
$("#download_undertaking").html('<button type="button" class="btn btn-info chk2" id=""><i class="fa fa-upload"></i></button>');
$("#msg").show();
setTimeout(function()
{
$("#msg").hide();
},
10000);
}
}
});
});
Controller
public function file_completion1($student_id='',$document_name='')
{
// if($this->input->post('student_id'))
// {
// echo $this->input->post($student_id);
// echo($student_id).'-';
// echo($document_name);
// exit();
$filename=array();
if(count($_FILES['copy_of_paid_fee_challan']['name']) > 0 && $_FILES['copy_of_paid_fee_challan']['name'] !='')
{
$files = $_FILES['copy_of_paid_fee_challan'];
$count = count($_FILES['copy_of_paid_fee_challan']['name']);
//echo $_FILES['file']['name'];exit();
for($i=0; $i<$count;$i++)
{
$config = array();
$projects_folder_path = './assets/uploads/';
$thumb = $projects_folder_path . 'thumb';
$_FILES['copy_of_paid_fee_challan']['name'] = $files['name'][$i];
$_FILES['copy_of_paid_fee_challan']['type'] = $files['type'][$i];
$_FILES['copy_of_paid_fee_challan']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['copy_of_paid_fee_challan']['error'] = $files['error'][$i];
$_FILES['copy_of_paid_fee_challan']['size'] = $files['size'][$i];
// $file_ext = ltrim(strtolower(strrchr($_FILES['copy_of_paid_fee_challan']['name'],'.')),'.');
// $file_name = 'oppein-'.date('YmdGis').'.'.$file_ext;
$config['upload_path'] = $projects_folder_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $_FILES['copy_of_paid_fee_challan']['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('copy_of_paid_fee_challan'))
{
$error_file_arr = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('err_message', $error_file_arr['error']);
$r=2;
echo json_encode($r);
exit();
}
else
{
$data['delete_record'] = $this->Common_model->select_single_records('uploads',$where=array('student_id'=>$student_id));
if(file_exists($projects_folder_path.$data['delete_record']['undertaking']))
{
unlink($projects_folder_path.$data['delete_record']['undertaking']);
}
$data_image_upload = array('upload_image_data' => $this->upload->data());
$image_name =$data_image_upload['upload_image_data']['file_name'];
$full_path = $data_image_upload['upload_image_data']['full_path'];
// ------------------------------------------------------------------------
$this->load->library('image_lib');
$config['image_library'] = 'GD2';
$config['source_image'] = './assets/uploads/' . $image_name;
$config['maintain_ratio'] = TRUE;
$config['master_dim'] = 'auto';
$config['quality'] = 70;
$config['width'] = 1024;
$config['height'] = 768;
$config['new_image'] = './assets/uploads/' . $image_name;
$this->image_lib->initialize($config);
$this->image_lib->resize();
// ------------------------------------------------------------------------
}
$filename[] = $image_name;
} // end for loop
}
foreach ($filename as $key => $value)
{
$insert_image=array(
'copy_of_paid_fee_challan'=> $value,
// 'student_id' => $student_id,
// 'stage_id' => $stage_id,
'update_date' => date("Y-m-d g:i:s"),
// 'category_status' => 1,
// 'user_id' =>$this->session->userdata('user_id'),
);
// echo "<pre>";
// print_r ($insert_image);
// echo "</pre>";
// exit();
$add_image = $this->Common_model->update_table('uploads',$where=array('student_id'=>$student_id),$insert_image);
}
if ($add_image)
{
$record = $this->Common_model->select_single_records('uploads',$where=array('student_id'=>$student_id));
echo json_encode($record);
}
// }
// else
// {
// $data['active']='registered_students';
// $this->load->view('admin/header',$data);
// $data['student_id']=$student_id;
// $data['error']='';
// $this->load->view('registration/file_completion',$data);
// $this->load->view('admin/footer',$data);
// }
}

Related

Impossible to upload file with buefy upload

I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}

Laravel saving image in storage

my code was working fine but now it is not, as image is not saving in folder, i am trying to save image in storage folder, with id as image name.
Controller:
if($request->hasFile('profile_pic')){
if (Input::file('profile_pic')->isValid()) {
$file = Input::file('profile_pic');
$destination = 'storage/app/teachers'.'/';
$ext= $file->getClientOriginalExtension();
$mainFilename = $teacher->id.request()->$ext;
$file->move($destination, $mainFilename.".".'jpg');
echo "uploaded successfully";
}
View: where 0000 is default image.
<div class="row">
<a href="#"> <img id="imgFileUpload" name="profile_pic" src={{asset('storage/app/teachers/'.'0000'.'.jpg')}} value="{{#$teacher->id}}"
onerror="this.src='storage/app/teachers/0000.jpg';" data-toggle="tooltip" data-placement="top" title="click to upload image" class="profile_pic rspimg shadow-sm bg-white rounded" id="imgFileUpload" data-toggle="tooltip" data-placement="top" title="Click To Upload image"></a>
<div class=" col-md-10">
<input type="file" name="profile_pic" id="FileUpload1" style="display: none" />
<span id="spnFilePath"></span>
</div>
</div>
ajax: to preview image in browser.
<script>
$(document).ready(function(){
$(function () {
alert(2);
$("#FileUpload1").change(function () {
var imgControlName = "#imgFileUpload";
readURL(this, imgControlName);
});
function readURL(input, imgControlName) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(imgControlName).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
var fileupload = $("#FileUpload1");
var image = $("#imgFileUpload");
image.click(function () {
fileupload.click();
});
});
});
</script>
Instead this $destination = 'storage/app/teachers'.'/';
try this $destination = storage_path() . '/app/teachers'.'/';
if ($request->hasFile('profile_pic')) {
$image = $request->file('profile_pic');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = Input::make($image->getRealPath());
$img->resize(120, 120, function ($constraint) {
$constraint->aspectRatio();
});
$img->stream(); // <-- Key point
//dd();
Storage::disk('local')->put('/app/teachers'.'/'.$fileName, $img, 'public');
}
try this one

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

Codeigniter image lib not resizing multiple images at once

I am trying to resize multiple images at once in my foreach loop but does not do it. It only resizes some of them per page.
Question how can I make sure it resizes the multiple images at once in my foreach loop on index()
As you can see it only resizes some of them the filemanager code is run/loaded ajax
<?php
class Filemanager extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('pagination');
}
public function index()
{
$data['resize_error'] ='';
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter;
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment - $per_page) {
$name = str_split(basename($image), 18);
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager') . '/?&directory=' . utf8_substr($image, utf8_strlen(FCPATH . 'image/' . 'catalog/')) . $url
);
} elseif (is_file($image)) {
// Resize function here
$data['images'][] = array(
'thumb' => $this->resize($image),
'name' => implode(' ', $name),
'type' => 'image',
'test' => '',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/'))
);
}
}
}
$this->load->view('common/filemanager_view', $data);
}
public function resize($filename) {
$this->load->library('image_lib');
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
return base_url('image/cache/') . $new_image;
}
}
This function below is called in the foreach loop on index
public function resize($filename) {
$this->load->library('image_lib');
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
return base_url('image/cache/') . $new_image;
}
Just the view for any one who wants it
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<div class="btn-toolbar mb-3" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group mr-2" role="group" aria-label="First group">
<a class="btn btn-dark" href="<?php echo $parent;?>" data-toggle="tooltip" data-placement="top" title="<?php echo $button_parent; ?>" id="button-parent" class="btn btn-default"><i class="fa fa-level-up"></i></a>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_upload; ?>" id="button-upload" class="btn btn-primary"><i class="fa fa-upload"></i></button>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_folder; ?>" id="button-folder" class="btn btn-dark"><i class="fa fa-folder"></i></button>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_delete; ?>" id="button-delete" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
</div>
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button"><i class="fa fa-search" aria-hidden="true"></i></button>
</span>
<input type="text" class="form-control" placeholder="Search for..." aria-label="Search for...">
</div>
</div>
</div>
<div class="modal-header justify-content-center">
<ol class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li class="breadcrumb-item"><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ol>
</div>
<div class="modal-body">
<!--
<div class="row">
<div class="col-sm-5">
<i class="fa fa-refresh"></i>
</div>
</div>
-->
<?php foreach (array_chunk($images, 4) as $image) { ?>
<div class="row">
<?php foreach ($image as $image) { ?>
<div class="col-sm-3 text-center">
<?php if ($image['type'] == 'directory') { ?>
<div class="text-center"><i class="fa fa-folder fa-5x"></i></div>
<label>
<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
<?php echo $image['name']; ?></label>
<?php } ?>
<?php if ($image['type'] == 'image') { ?>
<a href="<?php echo $image['href']; ?>" class="thumbnail">
<?php echo $image['thumb']; ?></a>
<label>
<input type="hidden" name="cache[]" value="<?php echo $image['cache']; ?>" />
<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
<?php echo $image['name']; ?></label>
<?php } ?>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<div class="modal-footer justify-content-center">
<?php echo $pagination; ?>
</div>
</div>
</div>
<script type="text/javascript"><!--
$('a.thumbnail').on('click', function(e) {
e.preventDefault();
<?php if ($thumb) { ?>
$('#<?php echo $thumb; ?>').find('img').attr('src', $(this).find('img').attr('src'));
<?php } ?>
<?php if ($target) { ?>
$('#<?php echo $target; ?>').attr('value', $(this).parent().find('input').attr('value'));
<?php } else { ?>
var range, sel = document.getSelection();
if (sel.rangeCount) {
var img = document.createElement('img');
img.src = $(this).attr('href');
range = sel.getRangeAt(0);
range.insertNode(img);
}
<?php } ?>
$('#modal-image').modal('hide');
});
$('a.directory').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('.pagination a').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('.breadcrumb-item a').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('#button-parent').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('#button-refresh').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('input[name=\'search\']').on('keydown', function(e) {
if (e.which == 13) {
$('#button-search').trigger('click');
}
});
$('#button-search').on('click', function(e) {
var url = 'admin/common/filemanager?&directory=<?php echo $directory; ?>';
var filter_name = $('input[name=\'search\']').val();
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
<?php if ($thumb) { ?>
url += '&thumb=' + '<?php echo $thumb; ?>';
<?php } ?>
<?php if ($target) { ?>
url += '?target=' + '<?php echo $target; ?>';
<?php } ?>
$('#modal-image').load(url);
});
//--></script>
<script type="text/javascript"><!--
$('#button-upload').on('click', function() {
$('#form-upload').remove();
$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" value="" /></form>');
$('#form-upload input[name=\'file\']').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);
$.ajax({
url: '<?php echo base_url('admin/common/filemanager/upload?');?>directory=<?php echo $directory; ?>',
type: 'post',
dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#button-upload i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>');
$('#button-upload').prop('disabled', true);
},
complete: function() {
$('#button-upload i').replaceWith('<i class="fa fa-upload"></i>');
$('#button-upload').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
}, 500);
});
$('#button-folder').popover({
html: true,
placement: 'bottom',
trigger: 'click',
title: 'New Folder',
content: function() {
html = '<div class="input-group">';
html += ' <input type="text" name="folder" value="" placeholder="New Folder" class="form-control">';
html += ' <span class="input-group-btn"><button type="button" title="" id="button-create" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></span>';
html += '</div>';
return html;
}
});
$('#button-folder').on('shown.bs.popover', function() {
$('#button-create').on('click', function() {
$.ajax({
url: 'admin/common/filemanager/folder?directory=<?php echo $directory; ?>',
type: 'post',
dataType: 'json',
data: 'folder=' + encodeURIComponent($('input[name=\'folder\']').val()),
beforeSend: function() {
$('#button-create').prop('disabled', true);
},
complete: function() {
$('#button-create').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
$('#modal-image #button-delete').on('click', function(e) {
if (confirm('Are You Sure')) {
$.ajax({
url: 'admin/common/filemanager/delete/',
type: 'post',
dataType: 'json',
data: {
path: $('input[name^=\'path\']:checked'),
cache: $('input[name^=\'cache\']').val()
},
beforeSend: function() {
$('#button-delete').prop('disabled', true);
},
complete: function() {
$('#button-delete').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
});
//--></script>
Try adding an error handler on resize() to see if there's an error that's preventing an image from getting resized:
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
Update
It seems the segment is not initialized correctly
$segment = $this->input->get('per_page');
Instead try
$segment = $this->input->get('page') * $this->input->get('per_page');
Solution
I have working solution now
I have had to make a check of the directory
if (!is_dir(DIR_IMAGE . 'cache/' . $new_image)) {
if ($this->input->get('directory')) {
#mkdir(DIR_IMAGE . 'cache/catalog/' . $this->input->get('directory') .'/', 0777, true);
} else {
#mkdir(DIR_IMAGE . 'cache/catalog/', 0777, true);
}
}
And also use use a if file exists for resize check and also codeigniter img() helper function helped also.
Full Controller
<?php
class Filemanager extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('pagination');
$this->load->library('image_lib');
$this->load->helper('html');
define('DIR_IMAGE', FCPATH . 'image/');
}
public function index()
{
$data['resize_error'] ='';
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter;
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
$this->load->model('admin/tool/image_model');
$this->load->helper('string');
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment - $per_page) {
$name = basename(preg_replace("/\.[^.]+$/", "", $image));
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => $name,
'href' => '',
'type' => 'directory',
'path' => substr($image, strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager/?&directory=' . substr($image, strlen(FCPATH . 'image/' . 'catalog/')) . $url)
);
} elseif (is_file($image)) {
$width = 100;
$height = 100;
$old_filename = substr($image, strlen(DIR_IMAGE));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
if (!is_dir(DIR_IMAGE . 'cache/' . $new_image)) {
if ($this->input->get('directory')) {
#mkdir(DIR_IMAGE . 'cache/catalog/' . $this->input->get('directory') .'/', 0777, true);
} else {
#mkdir(DIR_IMAGE . 'cache/catalog/', 0777, true);
}
}
if (!file_exists(DIR_IMAGE . 'cache/' . $new_image)) {
$config = array(
'image_library' => 'gd2',
'source_image' => $image,
'create_thumb' => false,
'maintain_ratio' => false,
'width' => $width,
'height' => $height,
'overwrite' => true,
'new_image' => DIR_IMAGE . 'cache/' . $new_image
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}
$data['images'][] = array(
'type' => 'image',
'href' => '',
'thumb' => img('image/cache/'. $new_image),
'name' => (strlen($name) > 13) ? substr($name,0,10).'...' : $name,
'path' => substr($image, strlen(DIR_IMAGE))
);
}
}
}
$data['heading_title'] = "Image Manager";
$data['text_no_results'] = "No Results";
$data['text_confirm'] = "Are You Sure";
$data['entry_search'] = "Search..";
$data['entry_folder'] = "New Folder";
$data['button_parent'] = "Parent";
$data['button_refresh'] = "Refresh";
$data['button_upload'] = "Upload";
$data['button_folder'] = "New Folder";
$data['button_delete'] = "Delete";
$data['button_search'] = "Search";
if (isset($input_get_directory)) {
$data['directory'] = $input_get_directory;
} else {
$data['directory'] = '';
}
// Return the filter name
if (isset($input_get_filter)) {
$data['filter_name'] = $input_get_filter;
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($input_get_target)) {
$data['target'] = $input_get_target;
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($input_get_thumb)) {
$data['thumb'] = $input_get_thumb;
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($input_get_directory)) {
$pos = strrpos($input_get_directory, '/');
if ($pos) {
$url .= '/?&directory=' . substr($input_get_directory, 0, $pos);
}
}
$data['parent'] = site_url('admin/common/filemanager' . $url);
// Refresh
$url = '';
if (isset($input_get_directory)) {
$url .= '/?&directory=' . $input_get_directory;
}
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['refresh'] = site_url('admin/common/filemanager' . $url);
$url = '';
if (isset($input_get_directory)) {
$url .= '?&directory=' . $input_get_directory;
}
if (isset($input_get_filter)) {
$url .= '&filter_name=' . $input_get_filter;
}
if (isset($input_get_target)) {
$url .= '/?&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$this->load->library('pagination');
$config['base_url'] = base_url('admin/common/filemanager' . $url);
$config['total_rows'] = $image_total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$config['num_links'] = "16";
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('common/filemanager_view', $data);
}
public function resize($filename) {
$this->load->library('image_lib');
//foreach ($filename as $key => $file) {}
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
return $this->image_lib->display_errors();
} else {
return base_url('image/cache/') . $new_image;
}
}
/**
* Codeigniter upload library with json and config_item
*/
public function upload()
{
$json = array();
$input_get_directory = $this->input->get('directory');
if (isset($input_get_directory)) {
$directory = 'image/catalog/' . $input_get_directory;
} else {
$directory = 'image/catalog';
}
$config['upload_path'] = './' . $directory . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$input_name = "file";
if ($this->upload->do_upload($input_name) == FALSE) {
$json['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$json['success'] = "This file" . ' ' . $file_data['file_name'] . ' ' . "has been uploaded";
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
public function folder()
{
$json = array();
$input_get_directory = $this->input->get('directory');
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->lang->line('error_directory');
}
if (!$json) {
$input_get_folder = $this->input->post('folder');
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($input_get_folder, ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->lang->line('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->lang->line('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
$json['success'] = $this->lang->line('text_directory');
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
public function delete()
{
$json = array();
$input_path_post = $this->input->post('path');
if (isset($input_path_post)) {
$paths = $input_path_post;
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(FCPATH . 'image/' . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == FCPATH . 'image/' . 'catalog') {
$json['error'] = $this->lang->line('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(FCPATH . 'image/' . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->lang->line('text_delete');
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
}

file upload is not working with ajax and codeigniter

i have a add form.added data using ajax and codeigniter.there is a file upload in that form.but file is not uploaded.other datas are added.but the file is not uploaded to the specified folder.
View file
<div class="row">
<div class="col-xs-6">
<label for="txtname">Title of Quotation Request :</label>
<input type="text" name="txtTitle" class="form-control" id="txtname" value="<?php
if (!empty($service)) {
echo $service;
}
?>" required>
</div>
<div class="col-xs-6">
<label for="txtcustomer">Select Customer :</label>
<select class="form-control" name="customer" id="customer" required="required">
<option value="">----Select------</option>
<?php
foreach ($customers as $customer) {
echo ' <option value="' . $customer->usr_id . '">' . $customer->usr_name . '</option>';
}
?>
</select>
<input type="hidden" name="" value="sbMerchant">
</div>
<div class="col-xs-12">
<label for="txtattachments">Drawing Attachments :</label>
<input name="txtattachments" type="file" id="txtattachments">
</div>
Ajax function
<script type="text/javascript">
$('#rfqsubmit').click(function () {
//var title = $('#title').val();
alert($('#txtattachments').val());
var form_data = {
title: $('#txtname').val(),
merid: $('#mermerchant').val(),
userid: $('#customer').val(),
description: $('#txtrequirement').val(),
reqid: $('#requirementid').val(),
shipmethod: $('#shipmethod').val(),
shiplocation: $('#shiplocation').val(),
txtattachments: $('#txtattachments').val(),
bidclose: $('#txtbidclose').val(),
shipcurrency:$('#shipcurrency').val(),
txtproduct:$('#txtproduct').val(),
txtunit:$('#txtunit').val(),
txtquantity:$('#txtquantity').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
dataType:"Json",
success: function(data) {
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
// window.location.href ="<?php //echo base_url() ?>moderator/RFQ/viewrfq/"+ form_data.reqid;
// alert('added Successfully');
}
});
return false;
});
</script>
Controller
public function addoffline() {
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$ip = $_SERVER['REMOTE_ADDR'];
$config['upload_path'] = 'assets/images/rfqimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['width'] = 75;
$config['height'] = 50;
if (isset($_FILES['txtattachments']['name'])) {
$filename = "-" . $_FILES['txtattachments']['name'];
$config['file_name'] = substr(md5(time()), 0, 28) . $filename;
}
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$field_name = "txtattachments";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('txtattachments')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat = array('upload_data' => $this->upload->data());
$this->resize($dat['upload_data']['full_path'], $dat['upload_data']['file_name']);
}
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
'rfq_requirementid'=>$this->input->post('reqid'),
'rfq_shipmethod'=>$this->input->post('shipmethod'),
'rfq_shiplocation'=>$this->input->post('shiplocation'),
'rfq_bidclosing'=>strtotime($this->input->post('bidclose')),
'rfq_shipcurrency'=>$this->input->post('shipcurrency'),
'rfq_productid'=>$this->input->post('txtproduct'),
'rfq_unit'=>$this->input->post('txtunit'),
'rfq_quantity'=>$this->input->post('txtquantity'),
'rfq_resource'=>2,
'rfq_dated'=>time(),
'rfq_status'=>0,
'rfq_ipadd'=>$ip
);
$inserted_id= $this->requirement_model->forminsert($data7);
$response=array('id'=>$inserted_id,'message'=>"inserted successfully");
echo json_encode($response);
die();
}
Instead of taking fields like that, do like this
var form_data = new FormData("id of the foem");
Then pass this in ajax like this,
data: form_data,
Make sure, enctype is set for form
enctype="multipart/form-data"
In codeingiter,
<?php echo form_open_multipart('moderator/RFQ/addoffline');?>
Try This:
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: "POST",
data: formData,
async: false,
success:function(data){
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
}
},
cache: false,
contentType: false,
processData: false
});
Check what data is coming inside addoffline() action using
print_r($this->input->post()) and print_r($_FILES) functions. According to your output you can implement your code.
Your problem will be solved.

Resources