ajaxFileUpload used in codeigniter - success function not executed - php

Good day to you all,
I am using ajaxFileUpload as below
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :"http://localhost/CodeIgniter_Registration/index.php/application_form/file_upload",
fileElementId :'userfile',
dataType : 'json',
data : {
'name' : $('#document_name').val()
},
success : function (data, status)
{
alert(data.msg);
}
});
return false;
});
at the controller, the file is uploaded, and the data to be returned is also present
which is returned as
echo json_encode(array('status' => $status, 'msg' => $msg));
from the controller
function file_upload() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png|doc|docx|pdf',
'upload_path' => $this->gallery_path,
'max_size' => 2000,
'file_name' => $filename
);
$this->load->library('upload', $config);
$test_upload = $this->upload->do_upload($file_element_name);
if (!$test_upload)
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
//$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if(1)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
echo json_encode(array('status' => $status, 'msg' => $msg));
}
But, the "success" callback never seems to be called, and no alert message is generated.
I have also tried returning some plain text. still nothing. hence, i don't think it is an issue with the json.
please suggest, what the issue can be!!

Related

Update query for API in codeigniter is not working

i want to write a API for updating data in sql. I am using CI for it.I am new to this field.while i have written it is not working in localhost itself .Can anyone help me? I am attaching my controller and model here.it is showing an error like this page is not working
function editprofile($id,$data) {
$this->db->where(array('user_id' => $id));
$this->db->update('registrationdetails', $data);
if(!empty($id))
{
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$adminId = 1;
$AUTHENTIC_KEY = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$user_id=2;
$firstname ="aiswarya";
$lastname ="mathew";
$email ="aiswarya#gmail.com";
$password ="aiswarya";
$confirmpassword ="aiswarya";
$contactnumber ="999999999";
$gender ="female";
$address ="canada";
$department ="cse";
$designation ="swe";
$Admindetails = $this->common->CheckValidAdmin($adminId,$AUTHENTIC_KEY);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id
);
$data = array();
$data = array('firstname'=>$firstname,'lastname'=>$lastname,'email'=>$email,'password'=>$password,'confirmpassword'=>$confirmpassword,'contactnumber'=>$contactnumber,'gender'=>$gender,'address'=>$address,'department'=>$department,'designation'=>$designation);
$status = $this->user->editprofile($user_id,$data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
function editprofile($data) {
if(!empty($data['user_id']))
{
$this->db->where(array('user_id' => $data['user_id']));
$this->db->update('registrationdetails', $data);
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$data['adminId'] = 1;
$data['AUTHENTIC_KEY'] = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$data['user_id']=2;
$data['firstname'] ="aiswarya";
$data['lastname'] ="mathew";
$data['email'] ="aiswarya#gmail.com";
$data['password'] ="aiswarya";
$data['confirmpassword'] ="aiswarya";
$data['contactnumber'] ="999999999";
$data['gender'] ="female";
$data['address'] ="canada";
$data['department'] ="cse";
$data['designation'] ="swe";
$Admindetails = $this->common->CheckValidAdmin($data['adminId'],$data['AUTHENTIC_KEY']);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id);
$status = $this->user->editprofile($data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}

Codeigniter uploading an image to a path folder but in the no record in the database

I need some help, I can upload an image to a folder path but in the database there is no record that i insert an image...
Here's my code
----Controller Code----
public function insert_product()
{
$this->form_validation->set_rules('product_name','Productname','required');
$this->form_validation->set_rules('product_price','Amount','required');
$this->form_validation->set_rules('product_stock','Stock','required');
$this->form_validation->set_rules('categorie_id','categorie_id','required');
$this->form_validation->set_rules('product_description','Description','required');
$config = array
(
'upload_path' => './assets/img',
'allowed_types' => 'jpg|png|jpeg|bmp',
'max_size'=> 0,
'filename' => $_FILES['product_image']['name']
);
$this->load->library('upload',$config);
if($this->upload->do_upload('product_image'))
{
$uploaddata = $this->upload->data();
$product_image=$uploaddata['file_name'];
// $this->db->insert('product',array('product_image'=>$this->upload->file_name));
}
if ($this->form_validation->run())
{
$data = $this->input->post();
unset($data['submit']);
$this->load->model('queries_product');
if($this->queries_product->insert_product($data))
{
$this->session->set_flashdata('msg','Successfully Inserted');
}
else
{
$this->session->set_flashdata('msg','Failed to Insert');
}
return redirect('inventory');
}
else
{
echo validation_errors ();
}
}
-----Model Code-------
public function insert_product($data)
{
return $this->db->insert('product',$data);
}
}
First Validate form
Then upload
if ($this->form_validation->run() != FALSE)
{
$data = array(
'product_name' => $this->input->post('product_name'),
'product_price' => $this->input->post('product_price'),
'product_stock' => $this->input->post('product_stock'),
'categorie_id' => $this->input->post('categorie_id')
);
$this->load->model('queries_product');
$this->load->library('upload',$config);
if(!$this->upload->do_upload('product_image'))
{
$this->session->set_flashdata('msg','Failed to Upload');
}
else
{
$uploaddata = $this->upload->data();
$product_image=$uploaddata['file_name'];
if($this->queries_product->insert_product($data))
{
$this->session->set_flashdata('msg','Successfully Inserted');
}
else
{
$this->session->set_flashdata('msg','Failed to Insert');
}
return redirect('inventory');
}
}
else
{
echo validation_errors ();
}
Something like this (as I mentioned in the comments)
if( false != ($valid = $this->form_validation->run()) && $this->upload->do_upload('product_image')){
$uploaddata = $this->upload->data();
$product_image=$uploaddata['file_name'];
// $this->db->insert('product',array('product_image'=>$this->upload->file_name));
$data = $this->input->post();
unset($data['submit']);
$this->load->model('queries_product');
if($this->queries_product->insert_product($data)){
$this->session->set_flashdata('msg','Successfully Inserted');
}else{
$this->session->set_flashdata('msg','Failed to Insert');
}
return redirect('inventory');
}else{
if(!$valid)
echo validation_errors();
else
$this->session->set_flashdata('msg','Failed to Upload');
}
By assigning false != ( $valid = ...) in the if condition, we can check on a failure which one actually failed, without doing any other real work.
Also as I mentioned in the comments the order of the arguments in the if are important. If validation is done first and returns false, PHP already knows the condition will not succeed. That's because the && requires that both sides be true and if one side is false there is no need to check the other side, so PHP immediately goes to the next condition in the block (the else in this case) without doing the upload.

getting file name as null by using var_dump

I have created file uploading function using ajax and codeigniter the problem is that when I am trying to upload an image it is working fine but when I try to upload document or excel file it is giving me null can anybody help me out to fix this issue
here is what error I am getting Array ( [error] => The filetype you are attempting to upload is not allowed.)
Here is my controller
public function post_forum() {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
$this->load->library('upload', $config);
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$dt = $this->upload->data();
$file = $dt['file_name'];
}
} else {
$file = '';
}
$word_dta = $this->input->post('post_dt');
$time_posted = time();
$user_id = $this->basic_model->is_login($this);
empty($this->input->post('group_id')) ? $group_id = '' : $group_id = $this->input->post('group_id');
empty($this->input->post('c_id')) ? $company_id = '' : $company_id = $this->input->post('c_id');
$data_upload = array(
'upload_document' => $file,
'discussion' => $word_dta,
'user_id' => $user_id,
'group_id' => $group_id,
'company_id' => $company_id,
'time_posted' => $time_posted,
'status' => 'Posted'
);
$post_id = $this->basic_model->insertRecord($data_upload, 'forums');
$data = array(
'file_name' => $file,
'data' => $word_dta,
'time_posted' => $time_posted,
'post_id' => $post_id,
'name' => $this->basic_model->getUserData(),
'command' => 'Submit Post'
);
$this->load->view('forum/includes/get_data', $data);
}
This is my html form which I have created in views folder
<form method="POST" action="" id="postform" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" id="imageFieldId" name="post_image" />
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
This is my ajax call
$(document).ready(function(e) {
$("#postform").on('submit', (function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
formData.append('post_dt', $("#contentbox").html());
$.ajax({
url : "http://tfsquare.com/demo/forums/post_forum",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
$("#contentbox").empty();
$('.no_st').css('display', 'none');
form.reset();
},
complete: function() {
$("#load").hide();
}
});
}));
});
$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
Codeigniter validate files not only with their extension but also with their MIME type. Probably Your given excel files doesn't have the mime entries in your Mimes.php which is located in config.php.
If you can find the content type add add it to the mime array in mimes.php. If not manually validate the extension by exploding the file name and Do not use codeigniter's 'allowed_types'.
Try this
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$ext = ['xls', 'xlsx'];
$dt = $this->upload->data();
$file = $dt['file_name'];
if( in_array($dt['file_ext'], $ext){
echo 'Valid File';
}
}
} else {
$file = '';
}

Cake php upload docx file return net::ERR_EMPTY_RESPONSE

I am trying to debug why docx and doc are always return net::ERR_EMPTY_RESPONSE,i also check Cake php error log but error log is showing blank, i am stuck to resolve this issue while pdf and xlsx are working file,please try to help me.below is my code
public function postDocumentForm() {
//die('Rashid');
$this->layout = 'Admin.ajax';
$this->autoRender = false;
$result = 'error';
$message = '';
$errors = '';
if(!$this->request->is('ajax')) {
exit(0);
}
if($this->request->is('post')) {
//pr($this->request->data); die;
$client_id = isset($this->request->data['Document']['client_id'])?$this->request->data['Document']['client_id']:null;
$category_id = isset($this->request->data['Document']['category_id'])?$this->request->data['Document']['category_id']:null;
if(!empty($client_id) && !empty($category_id)) {
$this->Document->create();
$this->Document->set($this->request->data);
$this->Document->setValidation('upload_client_document');
if($this->Document->validates() === true) {
$res = $this->_uploadFile($this->request->data['Document']['document']);
if($res !== false) {
$data['Document'] = array(
'category_id' => $category_id,
'description' => $this->request->data['Document']['description'],
'document' => $res['file_name'],
'file_path' => $res['file_path'],
'size' => $res['size'],
'type' => $res['type'],
'comment' => $this->request->data['Document']['comment'],
'is_required_signature' => isset($this->request->data['Document']['is_required_signature'])?$this->request->data['Document']['is_required_signature']:0,
'access' => $this->request->data['Document']['access'],
'uploaded_by' => $this->user_id
);
$data['ClientDocument'] = array('client_id'=>$client_id);
$this->Document->bindModel(
array(
'hasOne'=>array(
'ClientDocument' => array(
'className' => 'ClientDocument',
'foreignKey' => 'document_id'
)
)
)
);
if($this->Document->saveAll($data, array('validate'=>false))) {
if(isset($this->request->data['Document']['is_required_signature'])) {
$docid=$this->Document->id;
$this->hellosign($client_id,$docid);
}
$message = 'Document has been uploaded.';
$result = 'success';
} else {
$message = 'Document could not be uploaded please try again.';
$result = 'error';
}
} else {
$message = 'Document could not be uploaded please try again.';
$result = 'error';
}
} else {
$errors = $this->_validationHtmlErrors($this->Document->validationErrors);
$result = 'error';
$message = 'Please correct document validation errors.';
}
} else {
$message = 'Invalid action.';
$result = 'error';
}
} else {
$message = 'Invalid action.';
$result = 'error';
}
echo json_encode(array('result'=>$result, 'message'=>$this->_getMessage($message), 'errors'=>$errors));
}
and
$(document).on('submit', '#upload_client_document_form', function() {
var client_id = $('#doc_client_id').val();
var thisObj = $(this);
var formData = new FormData($(this)[0]);
var errorObj = $(this).parent().siblings('.client_document_upload_response');
/* Loader */
var document_upload_btn = $(this).find('#document_upload_btn');
var document_upload_btn_loading = $(this).find('#document_upload_btn_loading');
document_upload_btn.removeClass('active');
document_upload_btn.attr('disabled', true);
//document_upload_btn_loading.show();
console.log(BASE_URL+'documents/postDocumentForm');
var uploadedDocDivObj = thisObj.parents().eq(4).find('.cat_accord_upload_doc_div');
$.ajax({
url: BASE_URL+'documents/postDocumentForm',
type: 'POST',
data: formData,
beforeSend: function(data) {
console.log(data);
errorObj.removeClass('alert-error');
errorObj.removeClass('alert-success');
errorObj.hide();
$('#myloader').show();
},
success: function (data) {
console.log(data);
data = $.parseJSON(data);
var res_data = data.message;
//alert(data.errors);
document_upload_btn.addClass('active');
document_upload_btn.attr('disabled', false);
//document_upload_btn_loading.hide();
if (data.result == 'error') {
if (data.errors != '') {
res_data += data.errors;
}
errorObj.addClass('alert-error');
errorObj.html(res_data);
errorObj.show();
} else {
errorObj.addClass('alert-success');
errorObj.html(res_data);
errorObj.show();
thisObj[0].reset();
/* ajax for list uploaded documents start */
$.ajax({
url: BASE_URL+'documents/getUploadedDocuments/'+client_id+'/'+category_id,
data: '',
type: 'POST',
beforeSend: function(data){
uploadedDocDivObj.html(loadingImage);
},
success: function(data) {
uploadedDocDivObj.html(data);
}
});
/* ajax end */
}
$('#myloader').hide();
errorObj.delay(2000).fadeOut('fast');
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I actually had that problem some time ago, take a look in your query for excessively big returns, sometimes the browser stops when the returned array is gigantic, in that case use 'recursive' => -1 on the query.

Multiple file upload codeigniter not working

I have a form where multiple files can be uplaoded, along with a name field and a date field. The user can clone the inputs and upload as many certificates as they need. My HTML is below:
HTML:
<input type="file" name="certificate[]" />
<input type="text" name="certificate_name[]" class="right" />
<input type="text" name="expiry_date[]" />
I can upload the files one at a time but as multiple uploads it doesn't work, I get an error
A PHP Error was encountered
Severity: Warning
Message: is_uploaded_file() expects parameter 1 to be string, array given
Filename: libraries/Upload.php
Line Number: 161
PHP:
$uid = 1;
if(isset($_FILES['certificate']))
{
$this->uploadcertificate($uid, $this->input->post('certificate_name'), $this->input->post('expiry_date'));
}
function uploadcertificate($uid, $certificate, $expiry_date)
{
$status = "";
$msg = "";
$file_element_name = 'certificate';
$certificate_name = $certificate;
if ($status != "error")
{
$config['upload_path'] = './certificate_files/';
$config['allowed_types'] = 'pdf|doc|docx|txt|png|gif|jpg|jpeg|';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$file_id = $this->saveCertificate($uid, $data['raw_name'], $data['file_ext'], $certificate_name, $expiry_date);
}
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
//unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
function saveCertificate($uid, $file_name, $file_ext, $certificate_name, $expiry_date)
{
for ($ix=0; $ix<count($_FILES['certificate']); $ix++)
{
$insert_certificates = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates', $insert_certificates);
//return $insert; //you cant return here. must let the loop complete.
$insert_certificates_history = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates_history', $insert_certificates_history);
}
}
I'm confused as to exactly where I have went wrong. Can anyone point me in the right direction. Many thanks in advance!

Categories