How to upload image in codeigniter using ajax - php

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

Related

Update Data with Bootstrap Modal using CodeIgniter and Ajax

I'm trying to figure it out why I can't get the alert warning or success from the form validation in a modal. all I want at first is to update the data in the database and it work. now I can't see the alert whether it is wrong or correct, the modal close after I submit and how can I transfer the echo json_encode to alert in modal
view: layout view
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if (data.result){
$('#result').html('<p class="alert-success"> The inputs are insufficient </p>');
}else{
$('#result').html('<p class="alert-warning"> The profile successfully updated</p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="profile" id="1" href="#Profile_modal" data-toggle="modal">Profile</a>
<div class="modal" id="Profile_modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg modal-dialog-scrollable" >
<div class="modal-content">
<div class="modal-header bg-secondary">
<h5 class="modal-title text-white">Profile</h5>
<button type="button " class="close" data-dismiss="modal" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" >
<div class="text-center" id="result"> </div>
<div id="data_profile"> </div>
</div>
</div>
</div>
</div>
Controller: profile/profile_update
public function profile_update(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[13]');
$this->form_validation->set_rules('contact', 'Contact', 'trim|required|min_length[11]');
$this->form_validation->set_rules('hoax', 'Password',
'trim|required|min_length[6]|matches[confirm]');
$this->form_validation->set_rules('confirm', 'ConfirmPassword', 'trim|required|min_length[6]');
if ($this->form_validation->run() == FALSE) {
$data = array('profile_errors' => validation_errors());
echo json_encode(array("result"=>false));
}else{
$this->load->model('admin_model');
$data=$this->profile_model->update_data();
//$data = 'Your Profile Data has been Updated Successfully';
echo json_encode(array("result"=>true));
}
}
profile/get_fetchdata()
public function get_fetchdata(){
$Admin_id = $this->input->post('Admin_id');
if(isset($Admin_id) and !empty($Admin_id)){
$records = $this->profile_model->fetch_data($Admin_id);
$output = '';
foreach ($records->result_array() as $row) {
$attributes = array('id'=>'login_form', 'class'=>'form');
$output = '<div class="text-center" id="result"> </div>';
echo form_open('profile/profile_update', $attributes);
$output = '
<div class="form-group text-left">
<label> Username </label>
<input type="text" id="username" class="form-control" value='. $row["username"] .' placeholder="Enter Username" name="username" maxlength="10" required>
</div>
<div class="form-group text-left">
<label> Email </label>
<input type="Email" id="email" class="form-control" value='. $row["email"] .' placeholder="Enter Email" name="email" maxlength="20" required>
</div>
<div class="form-group text-left">
<label> Phone Number</label>
<input type="number" id="contact" class="form-control" value='.$row["contact"].' placeholder="Enter Phone Number" name="contact" maxlength="11" required>
</div>
<div class="form-group text-left">
<label> Password </label>
<input type="password" id="hoax" class="form-control" value='. $row["hoax"].' placeholder="Enter Password" name="hoax" maxlength="15" required>
</div>
<div class="form-group text-left">
<label> Confirm Password </label>
<input type="password" id="confirm" class="form-control" value='.$row["hoax"].' placeholder="Confirm Password" name="confirm" maxlength="15" required>
</div>
<input type="hidden" id="Admin_id" class="form-control" value='. $row["Admin_id"] .' name="Admin_id">
<input type="hidden" id="date" class="form-control" value='. $row["date_modified"] .' name="date">
<button class="btn btn-primary float-right new_profile" id="1" name="submit" type="submit" >Save</button>
<button class="btn btn-danger mx-2 float-right" data-dismiss="modal" type="button"> Cancel </button>';
echo form_close();
}
echo $output;
}else {
echo "Nothing to show";
}
}
if you use json as dataType, the browser will wait always for a JSON response, so the best thing to do here is the following:
if($this->form_validation->run() == FALSE){
echo json_encode(array("result" => false, "message" => "Failed"));
}else{
echo json_encode(array("result" => true, "message" => "Success!"));
}
and you can check the results on ajax side by using:
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if(data.result){
$('#adminId').val("");
$('#username').val("");
$('#email').val("");
$('#contact').val("");
$('#hoax').val("");
$('#confirm').val("");
$('#date').val("");
$('#result').html('<p class="alert-success"> ' + data.message + ' </p>');
}else{
$('#result').html('<p class="alert-warning"> ' + data.message + ' </p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});

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

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

upload image using codeigniter with ajax and formdata

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

TypeError: 'checkValidity' called on an object that does not implement interface HTMLTextAreaElement

I am facing this error and the email could not be sent because of this error. I have added a new extension Birthday reminder in opencart v2.0.1.1
I have searched about the error but could not resolve it. Please help. code for the file is this.
<form class="form mailForm">
<div class="row form-group" style="text-align: center; font-size: 18px;">
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>To: </label>
<strong><?php if(!empty($customerInfo['email'])) echo $customerInfo['email']; ?></strong>
<input type="hidden" name="customer_id" value="<?php if(!empty($customerInfo['customer_id'])) echo $customerInfo['customer_id']; ?>" />
<input type="hidden" name="to_mail" value="<?php if(!empty($customerInfo['email'])) echo $customerInfo['email'];?>" />
</div>
</div>
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>Born:</label>
<strong><?php if(!empty($customerInfo['birthday_date'])){
echo $customerInfo['birthday_date'];
}
?></strong>
</div>
</div>
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>Age:</label>
<strong>
<?php if(!empty($customerInfo['birthday_date'])) {;
$now = new DateTime("now");
if (strpos($customerInfo['birthday_date'],'/') !== false) {
echo floor((time()-strtotime(str_replace('/', '-', $customerInfo['birthday_date'])))/(365*60*60*24)) ;
} else {
echo floor((time()-strtotime($customerInfo['birthday_date']))/(365*60*60*24)) ;
}
}?>
</strong>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3">
<h5><strong><?php echo $discount_code_text ?></strong></h5>
</div>
<div class="col-xs-9">
<strong><?php echo $discount_code?></strong>
<input type="hidden" class="brSmallField form-control" name="discount_code" value="<?php echo $discount_code?>">
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $type_of_discount;?></strong></h5></div>
<div class="col-xs-3">
<select class="form-control" name="discount_type" >
<option value="P"><?php echo $percentage_text?></option>
<option value="F" <?php if(!empty($data['BirthdayReminder']['discount_type']) && $data['BirthdayReminder']['discount_type'] == "F") echo "selected";?>><?php echo $fixed_amount; ?></option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $discount_text;?></strong></h5></div>
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="brSmallField form-control" name="discount" value="<?php if(!empty($data['BirthdayReminder']['discount'])) echo $data['BirthdayReminder']['discount']; ?>">
<span class="input-group-addon" >%</span>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $total_amount; ?></strong></h5></div>
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="brSmallField form-control" name="total_amount" value="<?php echo $data['BirthdayReminder']['total_amount'] ?>">
<span class="input-group-addon" ><?php echo $currency ?></span>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span>Subject:</strong></h5></div>
<div class="col-xs-3">
<input placeholder="Mail subject" type="text" id="subject" class="form-control" name="subject" value="<?php if(!empty($data['BirthdayReminder']['subject'])) echo $data['BirthdayReminder']['subject']; else echo $default_subject; ?>" />
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $user_email; ?></strong></h5></div>
<div class="col-xs-9">
<textarea class="form-control" id="giftMessage">
<?php if(!empty($customerInfo)) {
$wordTemplates = array("{firstname}", "{lastname}", "{discount_code}");
$words = array($customerInfo['firstname'], $customerInfo['lastname'], $discount_code);
if(!empty($data['BirthdayReminder']['message'][$customerInfo['language_id']])) {
$message = str_replace($wordTemplates, $words,$data['BirthdayReminder']['message'][$customerInfo['language_id']]);
echo $message;
} else {
$default_message = str_replace($wordTemplates, $words, $default_message);
echo $default_message;
}
}?>
</textarea>
</div>
</div>
<div class="row form-group">
<div class="col-xs-4"> </div>
<div class="col-xs-4" style="text-align: center"><button class="btn btn-lg btn-primary" id="sendGift"><?php echo $send_gift_button; ?></button></div>
</div>
</form>
<script>
var gettingOptions = function () {
$('textarea[id="giftMessage"]').each(function(index, element) {
$('#'+element.id).summernote({
height:150
});
$('.btn#sendGift').on('click', function(e){
e.preventDefault();
var currentYear = new Date().getFullYear();
var errorInput = false;
if(!$('input[name="subject"]').val()){
e.preventDefault();
errorInput = true;
$('input[name="subject"]').css({'background':'#f2dede'});
}
if(!validateNumber($('input[name="discount"]'), e)) {
errorInput = true;
}
if(!validateNumber($('input[name="total_amount"]'), e)) {
errorInput = true;
}
if(!errorInput) {
var isSentGift = false;
var lastGift = "<?php if(isset($customerInfo['last_gift_date'])){ $date = explode('-', $customerInfo['last_gift_date']); echo $date[0]; } else { echo '0';}?>";
if(currentYear == lastGift){
isSentGift= true;
}
sentAgain = true;
if(isSentGift) {
var last_gift_date = "<?php if(!empty($customerInfo['last_gift_date'])) {
echo $customerInfo['last_gift_date'];
}
?>";
var sentAgain=confirm("A gift is sent to this customer on " + last_gift_date + ". Do you want to sent this again?");
}
if(sentAgain){
$.ajax({
url: 'index.php?route=<?php echo $modulePath;?>/sendGift&token=' + getURLVar('token') ,
dataType: 'html',
data:{
discount_code: $("input[name='discount_code']").val(),
discount: $("input[name='discount']").val(),
total_amount: $("input[name='total_amount']").val(),
discount_type: $("select[name='discount_type']").val(),
customer_id: $("input[name='customer_id']").val(),
to_mail: $("input[name='to_mail']").val(),
subject: $("input[name='subject']").val(),
gift_message: $('#'+element.id).summernote('code') },
type: 'POST',
dataType:"json",
success: function(data){
$('.messageHasBeenSent').show().delay(3000).fadeOut(600);
$('.btn.btn-link.active').click();
}
});
}
$("#sendEmailModal").modal('hide');
}
else {
e.preventDefault();
}
});
});
};
$("#sendEmailModal").on('shown.bs.modal', function (e) {
gettingOptions();
});
if($('select[name="discount_type"]').val() == 'P'){
$('#percentageAddonForm').show();
} else {
$('#currencyAddonForm').show();
}
$('select[name="discount_type"]').on('change', function(e){
if($(this).val() == 'P') {
$('#percentageAddonForm').show();
$('#currencyAddonForm').hide();
} else {
$('#currencyAddonForm').show();
$('#percentageAddonForm').hide();
}
});
function validateNumber(input, theEvent) {
var regex = /[0-9]|\./;
if(!regex.test(input.val())) {
input.css({'background':'#f2dede'});
return false;
} else {
return true;
}
}
</script>
I have got this resolved!
if(sentAgain){
$.ajax({
url: 'index.php?route=<?php echo $modulePath;?>/sendGift&token=' + getURLVar('token') ,
dataType: 'html',
data:{
discount_code: $("input[name='discount_code']").val(),
discount: $("input[name='discount']").val(),
total_amount: $("input[name='total_amount']").val(),
discount_type: $("select[name='discount_type']").val(),
customer_id: $("input[name='customer_id']").val(),
to_mail: $("input[name='to_mail']").val(),
subject: $("input[name='subject']").val(),
gift_message: $('#'+element.id).summernote('code') },
type: 'POST',
dataType:"json",
success: function(data){
$('.messageHasBeenSent').show().delay(3000).fadeOut(600);
$('.btn.btn-link.active').click();
}
});
}
This is the ajax call and this line was causing the problem
gift_message: $('#'+element.id).summernote('code')
So I change it with this
gift_message: $('#giftMessage').val()
the element was undefined in this case.

Categories