upload image using codeigniter with ajax and formdata - php

I like to upload image using codeigniter Framework in PHP with JQuery AJAX without redirecting the page. When i upload the image it redirecting to controller area and the values are not insert to database , ajax response also not coming ,
can any one pls solve my issue.... Thanks in advance...
This is my view area.
<form action="<?php echo site_url("Admin_Creator/do_upload")?>" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="frm_imageuupload" method="post">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my Ajax coding
$('#submit').on('click',function(){
var inputFile=$('input[name=file]');
var fileToUpload=inputFile[0].files[0];
var other_data = $('#frm_imageuupload').serializeArray();
var formdata=new FormData();
formdata.append(fileToUpload);
formdata.append(other_data);
//now upload the file using ajax
$.ajax({
url:"<?php echo base_url('Admin_Creator/do_upload') ?>",
type:"post",
data:formdata,
processData:false,
contentType:false,
success: function(data){
if (data== 'true'){
window.location.reload();
}
else{
alert("Pls Try Again");
}
}
});
This is my controller Coding...
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload()){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}
This is my model coding
public function save_imagepath($data1)
{
$this->db->insert('images', $data1);
return $this->db->insert_id();
}

Try This. It's working-
HTML Form-
<form enctype="multipart/form-data" id="submit">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" name="selectmenuid" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" name="selectsubmenu" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="sub">Submit</button>
</form>
Ajax -
$('#submit').submit(function(e){
e.preventDefault();
$.ajax({
url:'Your path',
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
alert(data);
}
});
});
Just set url in ajax, It would work perfectly.
Controller function-
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload("file")){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}

this is simple.
problem is the ajax
you should stop the form submit first
$('form').on('submit',function(e){//bind event on form submit.
e.preventDefault();//stop submit
......... //your other codes

This what i did to solve that problem
HTML
<div class="form-group">
<label for="logo">Service Provider Logo / Icon</label>
<input type="file" class="form-control" name="file" id="file" required="required">
<img src="#" id="img-logo" alt="image" class="img-responsive" style="height: 200px !important;">
<input type="hidden" class="" id="returned-sp-id">
</div>
<div class="form-group">
<label for="caption">Service Provider Name</label>
<input type="text" class="form-control" id="caption" required="required">
</div>
<div class="form-group">
<label for="details">Service Provider Details</label>
<textarea type="text" class="form-control" id="details" required="required"></textarea>
</div>
</form>
Jquery Ajax
$(function() {
$('#service-provider-details').on('submit', function(e){
var caption = $('#caption').val();
var details = $('#details').val();
var data = new FormData(this);
data.append('caption', caption);
data.append('details', details);
$.ajax({
url:'<?= base_url(), 'create_profile_sp/upload' ?>',
type:"post",
data: data,
processData:false,
contentType:false,
cache:false,
async:true,
success: function(data){
console.log(data);
}
});
e.preventDefault();
});
});
The controller
class Create_profile_sp extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('profile_sp_m');
}
public function upload($data) {
$data = $_POST;
$this->profile_sp_m->upload_logo($data);
}
}
The model
class profile_sp_m extends CI_Model
{
public $_tablename = 'profiles';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function upload_logo($data) {
$caption = $data['caption'];
$details = $data['details'];
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/jpeg") ) &&
($_FILES["file"]["size"] < 100000) &&
in_array($file_extension, $validextensions)){
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
$sourcePath = $_FILES['file']['tmp_name']; Store source path in a variable
$targetPath = "uploads/profiles/" . $_FILES['file']['name']; // The Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath); // Moving Uploaded file
// The Image Data
$imageData = [
'caption' => $caption,
'description' => $details,
];
// Insert the data
$this->db->insert($this->_tablename, $imageData);
}
}
}
}
}

Related

PHP OOP AJAX, getting errors from Controller

first of all, sorry for my english.
Well, I'm new to OOP PHP. I tried to develope a simple project and I would like to load data with Ajax to view changes without reloading pages.
I don't post models because they work fine and I can get all data I need.
But I have problems sending Controller errors and displaying them to the client.
I have a view called "viewUser.php" = main view.
In the main view is loaded "listUsers.php" in a div by an ajax call to display all the users, than each user has a button to send to another ajax call the id so this last ajax call can populate modal body with all the user informations in a form so they could be modified.
In this way all changes to user informations are displayed without reload the page but only with a ajax call in realtime.
I have this controller:
public function editUsers()
{
$data = [
'id' => '',
'name' => '',
'surname' => '',
'privilege' => '',
'position' => '',
'verified' => '',
'email' => ''
];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$surname = filter_var($_POST['surname'], FILTER_SANITIZE_STRING);
$privilege = filter_var($_POST['privilege'], FILTER_SANITIZE_STRING);
$position = filter_var($_POST['position'], FILTER_SANITIZE_NUMBER_INT);
$verified = filter_var($_POST['verified'], FILTER_SANITIZE_NUMBER_INT);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$data = [
'id' => trim($id),
'name' => trim($name),
'surname' => trim($surname),
'privilege' => trim($privilege),
'position' => trim($position),
'verified' => trim($verified),
'email' => trim($email),
];
$nameValidation = "/^[a-zA-Z]*$/";
//Valida il nome
if (empty($name)) {
$error['nameError'] = 'Perfavore, inserisci il tuo nome!';
} elseif (!preg_match($nameValidation, $name)) {
$error['nameError'] = 'Il nome può contenere solo lettere!';
}
//Controlla che gli errori siano vuoti
if (empty($error['nameError'])) {
$this->userManagementModel->editUser($data);
}
}}
called by ajax
function ajaxEditUser() {
$(document).on("click", "#editUser", function (event) {
event.preventDefault();
var id = $.trim($('#floatingInputId').val());
var name = $.trim($('#floatingInputName').val());
var surname = $.trim($('#floatingInputSurname').val());
var email = $.trim($('#floatingInputEmail').val());
var password = $.trim($('#floatingInputPassword').val());
var confirmPassword = $.trim($('#floatingInputConfirmPassword').val());
var privilege = $.trim($('#floatingSelectPrivileges').val());
var position = $.trim($('#floatingSelectPositions').val());
var verified = $.trim($('#floatingSelectVerified').val());
$.ajax({
url: URLROOT + '/usersManagement/editUsers',
type: 'post',
data: {
id: id,
name: name,
surname: surname,
email: email,
password: password,
confirmPassword: confirmPassword,
privilege: privilege,
position: position,
verified: verified
},
success: function (response) {
// Riaggiorna gli utenti
$(".loadAjax").load(URLROOT + '/usersManagement/listUsers');
$('#closeExampleModal').trigger('click');
}
});
});}
Data is sent from a form in a modal populated by another Ajax request that populates a view loaded into those modal
I would like to view the error generated by controls (if they exist) in editUsers function, into modal
This is ajax call that populates modal:
function ajaxModalUser() {
$(document).on("click", ".btnEditUser", function () {
var userid = $(this).data('id');
// Richiesta AJAX
$.ajax({
url: URLROOT + '/usersManagement/modalUserInfo',
type: 'post',
data: {userid: userid},
success: function (response) {
// Aggiunge il response nel body del modal
$('.modal-body').html(response);
// Apre il modal
$('#exampleModal').modal('show');
}
});
});
}.
here the controller for ajax request for modal:
public function modalUserInfo()
{
$data = [
'users' => '',
'privileges' => '',
'positions' => '',
'noResults' => ''
];
if (isset($_POST['userid'])){
$users = $this->userManagementModel->userInfo($_POST['userid']);
$privileges = $this->userManagementModel->selectPrivileges();
$positions = $this->userManagementModel->selectPositions();
$data = [
'users' => $users,
'privileges' => $privileges,
'positions' => $positions,
'noResults' => 'Nessun risultato'
];
}
$this->view('usersManagement/modalUserInfo', $data);
}
and here the page of the view loaded into modal
<?php
require APPROOT . '/views/includes/head.php';
?>
<div class="container">
<?php if (!empty($data)) {
foreach ($data['users'] as $user) :?>
<form method="post">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputId" name="id" value="<?php echo $user->id;?>" placeholder="id" hidden>
<label for="floatingInputId">Id</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectVerified" name="verified" value="" aria-label="Floating label select example">
<option <?php if ($user->verified == 2){ echo 'selected';} ?> value="2">VERIFICATO</option>
<option <?php if ($user->verified == 1){ echo 'selected';} ?> value="1">NON VERIFICATO</option>
</select>
<label for="floatingSelectVerified">Verifica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputName" name="name" value="<?php echo $user->name;?>" placeholder="nome">
<label for="floatingInputName">Nome</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputSurname" name="surname" value="<?php echo $user->surname;?>" placeholder="cognome">
<label for="floatingInputSurname">Cognome</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInputEmail" name="email" value="<?php echo $user->email;?>" placeholder="email">
<label for="floatingInputEmail">Email</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputPassword" name="password" value="" placeholder="password">
<label for="floatingInputPassword">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputConfirmPassword" name="confirmPassword" value="" placeholder="confirm password">
<label for="floatingInputConfirmPassword">Conferma Password</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPrivileges" name="privileges" value="" aria-label="Floating label select example">
<?php foreach ($data['privileges'] as $privilege) :?>
<option <?php if ($user->privilege_code == $privilege->privilege_code){ echo 'selected';} ?> value="<?php echo $privilege->privilege_code;?>"><?php echo $privilege->privilege;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPrivileges">Privilegi</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPositions" name="positions" value="" aria-label="Floating label select example">
<?php foreach ($data['positions'] as $position) :?>
<option <?php if ($user->position_id == $position->id){ echo 'selected';} ?> value="<?php echo $position->id;?>"><?php echo $position->user_position;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPositions">Carica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputCreationDate" name="creationDate" value="<?php if(!is_null($user->creation_date)){echo date("d/m/Y H:i:s", strtotime($user->creation_date));} else { echo "--";} ?>" placeholder="creato il" disabled>
<label for="floatingInputLastUpdate">Data registrazione :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastUpdate" name="lastUpdate" value="<?php if(!is_null($user->last_update)){echo date("d/m/Y H:i:s", strtotime($user->last_update));} else { echo "--";} ?>" placeholder="ultimo aggiornamento" disabled>
<label for="floatingInputLastUpdate">Ultima modifica :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastLogin" name="lastLogin" value="<?php if(!is_null($user->last_login)){echo date("d/m/Y H:i:s", strtotime($user->last_login));} else { echo "--";} ?>" placeholder="ultimo login" disabled>
<label for="floatingInputLastLogin">Ultimo login :</label>
</div>
</form>
<?php endforeach;
}?>
</div>
I tried many solutions, but I can't understand how send the error to the view of the modal and reloading it into modal.
Thanks to everybody

Can't upload image using ajax in codeigniter

I'm trying to upload an image to server but every time i get an error that "you did not select a file to upload"
I have created a form in my View where user details are asked and if candidate option is selected so user would be asked to select an image.
When I'm uploading an image and using jQuery to get a file path i'm getting "C://fakepath/filename.png" but for that also i also configured many things which worked and only return the file name.
I have already created a directory in root folder named upload but still i can't upload any image neither in upload folder nor on server.
View.php
<form method="POST" id="userForm" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-sm-12 col-md-6">
<label>First Name *</label>
<input type="text" name="firstName" class="form-control" value="<?php echo set_value('firstName'); ?>">
<span class="text-danger" id="name_error"><?php echo form_error('firstName'); ?></span>
</div>
<div class="form-group col-sm-12 col-md-6">
<label>Last Name *</label>
<input type="text" name="lastName" class="form-control" value="<?php echo set_value('lastName'); ?>">
<span class="text-danger"><?php echo form_error('lastName'); ?></span>
</div>
</div>
<h5 class="bg-dark text-white p-3 text-center mt-2 mb-4">User Credentials</h5>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" value="<?php echo set_value('email'); ?>">
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label>Password *</label>
<input type="password" name="password" class="form-control" value="<?php echo set_value('password'); ?>">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="form-group">
<label>Confirm Password *</label>
<input type="password" name="passwordMatch" class="form-control">
<span class="text-danger"><?php echo form_error('passwordMatch'); ?></span>
</div>
<h5 class="bg-dark text-white p-3 text-center mt-2 mb-4">User Status</h5>
<div class="form-group">
<label>User Status *</label>
<select class="form-control" id="userStatus" name="userStatus">
<option value="voter">Voter</option>
<option value="candidate">Candidate</option>
<option value="admin">Admin</option>
</select>
<span class="text-danger"><?php echo form_error('userStatus'); ?></span>
</div>
<div class="form-group" id="candidateSlogan">
<label>Candidate Slogan *</label>
<input type="file" name="userSlogan" class="form-control">
</div>
<button type="submit" class="btn btn-success">Add User</button>
</form>
ajax Response
<script type="text/javascript">
$("#userForm").submit(function(e){
e.preventDefault();
var firstName = $("input[name='firstName']").val();
var lastName = $("input[name='lastName']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
var passwordMatch = $("input[name='passwordMatch']").val();
var userStatus = $("#userStatus").val();
var slogan = $("input[name='userSlogan']").val();
if (userStatus == 'candidate') {
if(slogan == ''){
alert("Please Attach Candidate Slogan");
}
}
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>welcome/add_user_validation',
data: {
firstName: firstName,
lastName: lastName,
email: email,
password: password,
passwordMatch: passwordMatch,
userStatus: userStatus,
slogan: slogan
},
success: function(data){
$('#message').html(data);
if(data == 'User Added Successfully'){
$('#message').addClass("alert alert-success");
$('#message').removeClass("alert-danger");
$('#userForm')[0].reset();
$("input[name = 'firstName']").focus();
}
else{
$('#message').addClass("alert alert-danger");
$('#message').removeClass("alert-success");
}
},
error: function(data){
// alert(data);
$('#message').html(data);
}
});
});
</script>
Controller.php
public function add_user_validation(){
// $this->load->helper(array('form', 'url')) // already loaded in autoload.php;
// $this->load->library('form_validation') // declared in autoload.php;
$this->form_validation->set_rules("firstName", "First Name", "required|trim|alpha");
$this->form_validation->set_rules("lastName", "Last Name", "required|trim|alpha");
$this->form_validation->set_rules("email", "Email", "required|trim|valid_email");
$this->form_validation->set_rules("password", "Password", "required");
$this->form_validation->set_rules("passwordMatch", "Password Comfirmation", "required|matches[password]");
$this->form_validation->set_rules("userStatus", "User Status", "required");
if($this->input->post('userStatus') == 'candidate'){
$this->form_validation->set_rules("slogan", "Candidate Slogan", "required");
if(isset($_POST['slogan'])){
$config['upload_path'] = './upload/';
$config['upload_types'] = 'png|jpg|jpeg';
$this->load->library('upload', $config);
echo "<script>alert('hello')</script>";
if($this->upload->do_upload('slogan')){
$candidateSlogan = $this->upload->data();
// print_r($candidateSlogan);
}
else{
// echo $this->upload->display_erorrs();
// echo "This File type is not allowed";
// $candidateSlogan = NULL;
$error = array('error' => $this->upload->display_errors());
echo $error['error'];
// print_r($error);
}
}
}
else{
$candidateSlogan = NULL;
}
if ($this->form_validation->run()) {
$this->load->model('main_model');
$data = array(
"first_name" => $this->input->post('firstName'),
"last_name" => $this->input->post('lastName'),
"email" => $this->input->post('email'),
"password" => $this->input->post('password'),
"user_status" => $this->input->post('userStatus'),
// "slogan" => $this->input->post('userSlogan')
"slogan" => $candidateSlogan
);
// echo "<script>alert(" . $data . ")</script>";
print_r($data);
if($this->main_model->add_user($data)){
echo "User Added Successfully";
}
else{
// $error_msg = $this->db->error();
// echo $error_msg;
echo "User Already Exists";
// echo $this->db->error();
}
}
else{
echo validation_errors();
}
}
you need this in your form tag for files
enctype="multipart/form-data"
the in ajax call add following for files
cache:false,
contentType: false,
processData: false,
and use formdata instead of doing manually for each input
var formData = new FormData(this);
now your ajax should look like this
var formData = new FormData(this); // this will get all inputs from your form
$.ajax({
type:'POST',
url: '<?php echo base_url(); ?>welcome/add_user_validation',
data:formData,
cache:false,
contentType: false,
processData: false,
error: function(data){
console.log("error");
console.log(data);
},
success:function(data){
console.log("success");
console.log(data);
},
});

How to upload image in codeigniter using ajax

Here is my code,
Please check this, Iam trying to upload image its not working. Iam passing data through ajax using id.
Iam getting image name, while passing through codeigniter its showing error undefined user_img
Below code is Ajax
$('#profile_set').validate({
submitHandler: function(form) {
user_zip = $("#user_zip").val();
first_name = $("#xx_first_name").val();
db_email = $("#db_email").val();
datepicker = $("#datepicker").val();
last_name = $("#xx_last_name").val();
new_image = $("#new_image").val();
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
fileElementId :'new_image',
dataType: 'json',
data: {
xx_first_name: first_name,
xx_last_name: last_name,
db_email: db_email,
db_dob: datepicker,
user_zip: user_zip,
user_img: new_image
},
success: function (data) {
if(data.status == 'success'){
$('#message').removeClass('alert alert-danger');
$('#message').addClass('alert alert-success');
$('#message').empty();
$('#message').append(data.message);
$('#message').fadeOut(3000);
}
else if(data.status == 'fail') {
$('#message').removeClass('alert alert-success');
$('#message').addClass('alert alert-danger');
$('#message').empty();
$('#message').append(data.message);
}
}
});
}
});
In this function am getting image name, Its showing undefined index of profile_img['file_name' => $_FILES['user_img']['name'] ]
public function profile($id)
{
$user_id = $id;
$profile_img = $this->input->post('user_img');
if ($user_id !== '' AND $user_id > 0) {
if(!empty($profile_img)){
$uploadconfig = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '204800',
'file_name' => $_FILES['user_img']['name'],
'encrypt_name' => TRUE
);
print_r($uploadconfig); exit;
$this->load->library('upload', $uploadconfig);
if ( ! $this->upload->do_upload("user_img")) {
echo "failed to upload file(s)";
}
$this->upload->initialize($uploadconfig);
$this->upload->do_upload("user_img");
$upload_data = $this->upload->data();
$user_profile = $upload_data['file_name'];
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
$data['user_img'] = $user_profile;
}
else {
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
}
$update_set = $this->users->update($id, $data);
if ($update_set)
{
$ret['status'] = 'success';
$ret['message'] = 'Updated successfully';
echo json_encode($ret);
}
else
{
$ret['status'] = 'fail';
$ret['message'] = 'Error while updating';
echo json_encode($ret);
}
}
}
My forum Code
<div class="account_forum" id="profile">
<h2 class="forum_title">Profile</h2>
<form id="profile_set">
<div class="row row_space">
<div class="col-md-10">
<a class="profile-pic" id="existing_pic">
<div class="profile-pic" style="background-image: url('<?php echo base_url('uploads/')?><?php echo #$users->user_img ?>')" >
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
<input type='file' name="new_image" id="new_image" onchange="readURL(this);" style="display:none;" />
<a class="profile-pic" id="new_upload">
<div class="profile-pic" id="view_image">
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>First Name</label>
<input type="text" name="xx_first_name" id="xx_first_name" class="form-control" placeholder="John" value="<?php echo set_value('xx_first_name', #$users->first_name);?>" required>
</div>
<div class="col-md-5">
<label>Last Name</label>
<input type="text" name="xx_last_name" id="xx_last_name" class="form-control" placeholder="Doe" value="<?php echo set_value('xx_last_name', #$users->last_name);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Email</label>
<input type="text" name="db_email" class="form-control" id="db_email" placeholder="jdoe#gmail.com" value="<?php echo set_value('db_email', #$users->email);?>" required>
</div>
<div class="col-md-5">
<label>Birthday</label>
<input type="text" name="db_dob" class="form-control" data-toggle="datepicker" placeholder="00/0/0000" id="datepicker" value="<?php echo set_value('db_dob', #$users->user_dob);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Postal Code</label>
<input type="text" id="user_zip" name="user_zip" class="form-control" placeholder="00000" value="<?php echo set_value('xx_user_zip', #$users->user_zip);?>" required>
</div>
</div>
<input type="hidden" id="profile_old" name="profile_old" value="<?php $users->user_img; ?>">
<div class="row row_space">
<div class="col-md-5">
<button type="submit" name="" class="acct_btn" value="Update">Update Profile</button>
</div>
</div>
</form>
</div>
for upload new image to server with ajax, you need to use new FormData():
var fd = new FormData();
fd.append( 'user_zip', user_zip);
fd.append( 'xx_first_name', first_name);
fd.append( 'db_email', db_email);
fd.append( 'db_dob', datepicker);
fd.append( 'xx_last_name', last_name);
fd.append( 'user_img', $('#new_image')[0].files[0]);
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
data: fd,
success: function () {
// do something
}
});

Error file Upload Codeigniter Ajax

Error loading file to server and check everything and apparently it's okay please help
enter image description here
View
<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>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="txtProdId" value="0">
<div class="form-group">
<label for="category" class="label-control col-md-4">Nombre categoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtId" id="categoria">
</select>
</div>
</div>
<div class="form-group">
<label for="subcategory" class="label-control col-md-4">Nombre subcategoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtSubId" id="subcategoria">
</select>
</div>
</div>
<div class="form-group">
<label for="codig" class="label-control col-md-4">Codigo</label>
<div class="col-md-8">
<input type="text" name="txtCodigo" class="form-control">
</div>
</div>
<div class="form-group">
<label for="name" class="label-control col-md-4">Nombre Producto</label>
<div class="col-md-8">
<input type="text" name="txtProducto" class="form-control">
</div>
</div>
<div class="form-group">
<label for="description" class="label-control col-md-4">Descripción</label>
<div class="col-md-8">
<textarea class="form-control" name="txtDescripcion"></textarea>
</div>
</div>
<div class="form-group">
<label for="picture" class="label-control col-md-4">Imagen</label>
<div class="col-md-8">
<input type="file" name="txtFoto" id="txtFoto">
</div>
</div>
<div class="form-group">
<label for="cant" class="label-control col-md-4">Cantidad</label>
<label for="catalog" class="label-control col-md-4">Precio catálogo</label>
<label for="ofert" class="label-control col-md-4">Precio oferta</label>
</div>
<div class="input-group">
<div>
<input type="text" name="txtCantidad" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtCatalogo" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtOferta" class="form-control">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="button" id="btnSave" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
Jquery ajax View
$(function(){
showAllProduct();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Registrar Producto');
$('#myForm').attr('action', '<?php echo base_url() ?>producto/addProduct');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var codig = $('input[name=txtCodigo]');
var productName = $('input[name=txtProducto]');
var description = $('textarea[name=txtDescripcion]');
var cant = $('input[name=txtCantidad]');
var catalog = $('input[name=txtCatalogo]');
var ofert = $('input[name=txtOferta]');
var myFile = $("#txtFoto").val();
alert(myFile);
var result = '';
if(codig.val()==''){
codig.parent().parent().addClass('has-error');
}else{
codig.parent().parent().removeClass('has-error');
result +='1';
}
if(productName.val()==''){
productName.parent().parent().addClass('has-error');
}else{
productName.parent().parent().removeClass('has-error');
result +='2';
}
if(description.val()==''){
description.parent().parent().addClass('has-error');
}else{
description.parent().parent().removeClass('has-error');
result +='3';
}
if(cant.val()==''){
cant.parent().parent().addClass('has-error');
}else{
cant.parent().parent().removeClass('has-error');
result +='4';
}
if(catalog.val()==''){
catalog.parent().parent().addClass('has-error');
}else{
catalog.parent().parent().removeClass('has-error');
result +='5';
}
if(ofert.val()==''){
ofert.parent().parent().addClass('has-error');
}else{
ofert.parent().parent().removeClass('has-error');
result +='6';
}
//if()
if(result=='123456'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'añadido';
}else if(response.type=='update'){
var type ='actualizado';
}
$('.alert-success').html('Producto '+type+' con éxtito').fadeIn().delay(4000).fadeOut('slow');
showAllProduct();
}else{
alert('Error');
}
},
error: function(){
alert('No se puede añadir el dato');
}
});
}
});
});
Controller: The file 'txtFoto' does not arrive is as if it had been sent from the form
public function addProduct(){
$pathArchivo = $this->filePath();
$result = $this->m->addProduct($pathArchivo);
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function filePath(){
$archivo=$_FILES['txtFoto'];
$config['upload_path'] = realpath(APPPATH.'../image/product/');
//$config['file_name'] = "nombre_archivo";
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['max_size'] = "50000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
$res = '';
if ( ! $this->upload->do_upload($archivo)) {
$error = array('error' => $this->upload->display_errors());
$res = 'hola no funciona';
print_r($error);
}else {
$file_data = $this->upload->data();
$file_path = './image/product/'.$file_data['file_name'];
$res = $file_path;
//print_r($data);
}
return $res;
}
Model
public function addProduct($path){
$field = array(
'sub_id'=>$this->input->post('txtSubId'),
'pr_codigo'=>$this->input->post('txtCodigo'),
'pr_nombre'=>$this->input->post('txtProducto'),
'pr_descripcion'=>$this->input->post('txtDescripcion'),
'pr_cantidad_stock'=>$this->input->post('txtCantidad'),
'pr_precio_catalogo'=>$this->input->post('txtCatalogo'),
'pr_precio_oferta'=>$this->input->post('txtOferta'),
'pr_foto'=>$path
);
$this->db->insert('producto', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Your method is correct if you are trying to send a TEXT file.
Before you continue doing it with AJAX ,
Lets try and send the file normally
and you would want to receive it like this
$this->upload->do_upload('txtFoto');
I am just curious , If you are using ci's upload handler , why do you take it from PHP's $_FILE?
$_FILES['txtFoto']
Can you share any var_dump from $_FILES?
EDIT
You can do it via AJAX using FormData
var formData = new FormData($('#myForm'))
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
success: function(response){
//handle success
},
error: function(){
//handle error
alert('No se puede añadir el dato');
}
});
On the Controller ,
Initialize your upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
And make sure that the directory you want to upload your image is writable

Image upload not working with event.preventDefault() CodeIgniter

I have created a form in CodeIgniter for uploading an image.
The View file:
<form method="POST" action="<?php echo base_url().'promotions/add_item' ?>" enctype='multipart/form-data' class="form-horizontal" id="addItem">
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
</form>
The Ajax code:
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#addItem").serialize(),
type: $(this).attr('method')
}).done(function(data) {
$('#ret').html(data);
// window.location.reload();
$('#addItem')[0].reset();
});
event.preventDefault();
});
});
</script>
The Controller file:
<?php
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
var_dump($_FILES['pro_image']);
if ($this->form_validation->run() == FALSE) {
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
} else {
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('pro_image')) {
echo 'Error :'. $this->upload->display_errors();
}
$data = $this->upload->data();
$img = $data['file_name'];
}
$title = $this->input->post('title');
$description = $this->input->post('description');
$this->promotions_model->add_item($title, $description,'uploads/'.$img);
}
Whenever I attempt to upload an image it always comes as null, but if I comment out the event.preventDefault(); line then upload an image, then it works fine. However, then the other functionality like validation and return messages fail to work properly.
Can any one please tell me what is issue with event.preventDefault()?
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
event.preventDefault();
var url = $(this).attr('action');
var data= new FormData($("#addItem")[0]);
$.ajax({
url: url,
contentType:false,
cache:false,
processData:false,
data: data,
type: 'POST' // POST/GET
success:function(data) {
$('#ret').html(data);
$('#addItem')[0].reset();
}
});
});
});
Add event.preventDefault(); in the begining sumbit listner

Categories