what should I do if i can't upload an image in a form it successfully created but the file is shows 0 not the upload file. please help me thanks in advance!
script in view where I can update and add a single form with upload
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#dataTable2').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('about/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add About US'); // Set Title to Bootstrap modal title
}
function edit_person(about_id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('about/ajax_edit/')?>/" + about_id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="about_id"]').val(data.about_id);
$('[name="about_details"]').val(data.about_details);
$('[name="images"]').val(data.image);
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('about/ajax_add')?>";
}
else
{
url = "<?php echo site_url('about/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#myModal').modal('hide');
reload_table();
if (empty($_FILES['image'])) {
return FALSE;
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_person(about_id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('about/ajax_delete')?>/"+about_id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
This is my form
<div class="modal-body form">
<form action="#" id="form">
<input type="hidden" value="" name="about_id"/>
<!-- <div class="form-group has-feedback ">
<label>Date</label>
<input type="date" id="date" class="form-control" input-sm placeholder="Date"/>
</div>-->
<div class="form-group has-feedback">
<label>About Details</label>
<input type="text" id="title" name="about_details" class="form-control" input-sm placeholder="About Details"/>
</div>
<!-- Description -->
<div class="form-group has-feedback">
<label>Image</label>
<?php $attrib = array('type'=>'text','name'=>'image','class'=>'form-control','id'=>'file'); ?>
<?php echo form_upload( $attrib,set_value('image')); ?>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-success" aria-hidden="true" onclick="save()">Save</button>
my controller for add and update
public function ajax_add()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$this->person->update(array('about_id' => $this->input->post('about_id')), $data);
echo json_encode(array("status" => TRUE));
}
What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:
$('#uploadimg').ajaxForm({
//uploadimg is my form id
dataType: 'json',
success: processJson
});
function processJson(data) {
if(data.msg=="success"){
alert('Upload is successful.');
}
else{
alert('Upload couldn't be completed.');
}
}
The form would be
<form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">
On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.
public function uploadImage(){
//$id = $this->session->userdata('uid');
$config[ 'upload_path' ] = UPLOAD_DIR.'/newsletter/0';
$config[ 'allowed_types' ] = 'gif|jpg|png';
$config[ 'max_size' ] = '1500';
$config[ 'max_width' ] = '1000';
$config[ 'max_height' ] = '1500';
$image_name = "files";
$this->load->library( 'upload', $config );
if ( $this->upload->do_upload( $image_name ) ) {
$upload_data = $this->upload->data();
if(!empty($upload_data)){
$arg = array(
'name' => $upload_data[ 'file_name' ]
);
$this->modelName->insert($arg );
$data['msg']="success";
}
else{
$data['errmsg']="Couldnot upload the file!";
}
}
else{
$data['errmsg'] =$this->upload->display_errors();
}
echo json_encode($data);
}
Now this will trigger the processJson function in the script. And the upload shows the result.
You can find the javascript file on jquery.form.js.
I hope it works out for you.
Related
I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
In my CodeIgniter project I need to insert data into db table, I am having
Internal server error (500)
issues to add data to database using Ajax.
My Ajax code is below,
$("#rsvp_form").validate({
rules: {
uname: {
required: true,
minlength: 8
},
uemail: "required",
umessage: {
required: true,
maxlength: 100
}
},
messages: {
uname: {
required: "Please enter your name",
minlength: jQuery.validator.format("At least 8 characters required!")
},
uemail: "Please enter your email",
umessage: {
maxlength: jQuery.validator.format("Please enter no more than 100 characters!")
},
},
// ajax request
submitHandler: function (form) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
// loader
$(".loader").show();
// ajax request
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Welcome/create_wish",
data: formData,
dataType: "json",
success: function (data) {
// if send data successfull
if (data.status === 'success') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-success").show("slow");
}, 300);
// if send data something wrong
} else if (data.status === 'error') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-error").show("slow");
}, 300);
}
}
});
return false;
}
});
My Welcome Controller function is below : ,
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_wish' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model_wishes Model is here,
function createWish($data) {
$this->db->insert("wishes", $data);
}
welcome_message View is,
<form id="rsvp_form" action="">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
When Post Wish button is clicked getting XHR failed loading: POST and an error
POST http://localhost/CodeIgniterProj/index.php/Welcome/create_wish 500 (Internal Server Error)
Please let me know what actually force to internal server error, and how could I fix this Issue.
You are using wrong post input, please check below updated code
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('user_name'),
'user_email' => $this->input->post('user_email'),
'user_wish' => $this->input->post('user_wish')
);
$this->model_wishes->createWish($data);
}
Hope this will help you :
Your submitHandler code should be like this :
submitHandler: function (form)
{
var formData = $(form).serialize();
$(".loader").show();
console.log(formData);
$.ajax({
type: "POST",
url: "<?=site_url('Welcome/create_wish'); ?>",
data: formData,
dataType: "json",
success: function (data) {
alert(data);
}
});
}
And your controller create_wish should be like this :
public function create_wish()
{
$this->load->model("model_wishes");
$user_name = $this->input->post('uname'));
$user_email = $this->input->post('uemail');
$user_wish = $this->input->post('umessage');
$data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_wish' => $user_wish
);
$this->model_wishes->createWish($data);
$response = array('status' => 'success');
echo json_encode($response);
}
Instead of base_url use the site_url
site_url('Welcome/create_wish')
I have this AJAX message form:
HTML:
<form class="" id="message-form" action="message-send.php" method="POST">
<div class="form-group">
<textarea name="message" id="message-field" rows="3" class="form-control message-field"></textarea>
</div>
<div class="form-group">
<input type="file" id="file" name="file">
</div>
<div class="form-group text-right">
<input type="submit" id="submit" class="btn btn-success btn-sm msg-send" value="Envoyer" disabled>
</div>
</form>
JavaScript:
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
data: message_form.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
PHP:
require 'config.php';
$message = $_POST['message'];
$query = 'INSERT INTO messages (time, from, to, message, file) VALUES (?, ?, ?, ?, ?)';
if (!($stmt = $mysqli->prepare($query))) {
echo $mysqli->error;
}
$stmt->bind_param('iiiss', $time, $from, $to, $message, $file);
$stmt->execute();
$stmt->close();
$mysqli->close();
Now what I need:
Upload the file using AJAX
Store the file as is to "/uploads/" with the same name
Put the filename in the db with the message
NB: The form already works well (The code presented is just a minimal version) I just need the handling of the file.
You have not included mimetypes in your ajax request.
mimeTypes: "multipart/form-data" add this inside ajax
try sending input values with formdata
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
var message_form = $('#message-form');
var file = $('#file');
var formdata = new FormData();
formdata.append('file', file.files[0]);
formdata.append('message', $('#message-field').val());
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
mimeTypes: "multipart/form-data,
data: formdata,
async: true,
contentType: false,
processData: false,
beforeSend: function(){
},
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}
I am trying to upload a file with some other data. The thing is I'm getting the error that You did not select a file to upload. I can't understand what is it that I'm doing wrong. I would be really glad if anybody can point out what is it that I am doing wrong. Thanks
html file
<div class="modal-body">
<form id="add_message" enctype="multipart/form-data" method="post" action="<?php echo base_url() ?>apps/messages/composeMessage">
<div class="form-group">
<select id="messageTo" class="form-control" data-plugin="select2" multiple="multiple" data-placeholder="To:" name="messageTo">
</select>
</div>
<div class="form-group">
<input class="form-control" placeholder="Subject" id="messageSubject" name="messageSubject"></input>
</div>
<div class="form-group">
<textarea data-provide="markdown" data-iconlibrary="fa" rows="10" id="messageBody" name="messageBody"></textarea>
</div>
<input type="hidden" name="fname" value="" id="formName" ></input>
<div class="left">
<!-- <span class="btn green fileinput-button"> -->
<input id="message_attachement" type="file" name="file_attac" size="20" >
<!-- </span> -->
</div>
<!-- <button class="btn btn-primary" type="submit" value="submit">Send</button> -->
</form>
</div>
<div class="modal-footer text-left">
<button class="btn btn-primary" data-dismiss="modal" id="addformButton">Send</button>
<button class="btn btn-primary" data-dismiss="modal" id="saveformButton">Save</button>
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Cancel</a>
</div>
JS
$("#addformButton").on('click' , function(){
debugger;
$.ajax({
type: "POST",
url: base_url + "apps/messages/composeMessage",
async: false,
mimeType: "multipart/form-data",
dataType:JSON,
data:{
'reciever': $('#messageTo').val() ,
'subject': $('#messageSubject').val(),
'text': $('#messageBody').val(),
'type': 'active',
'msgId': $('#formName').val(),
'attachment' : $('#message_attachement').val()
},
success: function(response){
},
error: function(response){
}
});
});
Controller
$this->load->helper('file_upload');
$filename = $this->input->post('attachment');
$path = 'uploads/attachments/';
$allowed_types = 'erb|php|txt';
$redirect = '';
// error_log("outside");
if (!empty($this->input->post('attachment'))) {
// error_log("inside");
// error_log ("Parameters: " . $path." Types: ". $allowed_types." name: ". $filename." redirect: ". $redirect);
$parameters['profile_pic'] = file_upload($path, $allowed_types, $filename, $redirect);
// error_log("The path is ");
// error_log($parameters['profile_pic']);
if ($this->session->set_userdata("img_errors")) {
// error_log("error");
return false;
}
}
File Upload function
function file_upload($upload_path , $allowed_types , $filename , $redirect)
{
$ci = & get_instance();
$config['upload_path'] = $upload_path;
$config['allowed_types'] = $allowed_types;
// $config['max_size'] = 1024;//1mb
// $config['max_width'] = 1024;
// $config['max_height'] = 1024;
$ci->load->library('upload', $config);
$data = NULL;
if (!$ci->upload->do_upload($filename)) {
error_log("within the file");
// $error = array('error' => $ci->upload->display_errors());
error_log($ci->upload->display_errors());
$ci->session->set_userdata('img_errors', $ci->upload->display_errors());
//error_log(print_r($ci->upload->display_errors(),true));
// redirect(base_url() . $redirect);
} else {
error_log("uploading");
$data = array('upload_data' => $ci->upload->data());
// do_resize($config['upload_path'] , $data['upload_data']['file_name']);
}
return $config['upload_path'] . $data['upload_data']['file_name'];
}
This is the working code I used in my most recent project, the code is self explanatory however feel free to ask any question.
HTML:
<form action="http://localhost/index.php/upload_file" method="post" style="display:none;" id="file_upload_form" enctype="multipart/form-data">
<input type="file" id="dialog_triggerer" name="uploaded_file">
</form>
<button class="btn btn-default btn-fab-sm" id="file_attach">
<span class="mdi-file-attachment"></span>
</button>
JS:
trigger this code on some action:
var form = $('form')[0]; // standard javascript object here
var formData = new FormData(form);
if($("#dialog_triggerer").val()!=""){
$.ajax( {
url: FRONTEND_URL + '/upload_file',
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: false
} ).done(function(data){
file_data = JSON.parse(data);
new_post.file_data = file_data;
});
}
upload_file ctrl:
<?php
class Upload_file extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$valid_file=true;
$message;
//if they DID upload a file...
if($_FILES['uploaded_file']['name'])
{
//if no errors...
if(!$_FILES['uploaded_file']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['uploaded_file']['name']); //rename file
if($_FILES['uploaded_file']['size'] > (20024000)) //can't be larger than 20 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
$file_path = 'themes/uploads/'.$new_file_name;
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], FCPATH . $file_path);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['uploaded_file']['error'];
}
}
$save_path = base_url().$file_path;
$name = $_FILES['uploaded_file']['name'];
$size = $_FILES['uploaded_file']['size'];
$type = $_FILES['uploaded_file']['type'];
$data = array(
"message" => $message,
"save" => $save_path,
"name" => $name,
"size" => $size,
"type" => $type
);
$this->load->view('upload_file/upload_file.php', $data);
}
}
upload_file.php view:
<?php
$res = array(
"msg" => $message,
"path" => $save,
"name" => $name,
"size" => $size,
"type" => $type
);
echo json_encode($res);
?>
Just found out I had not posted the solution that helped me for this problem. Here's what I did
The real problem was with sending the file to the server. I just needed to set the cache, processData and contentType to false and that worked for me.
and one more thing I needed to send data to the server using form data.
I have posted the relevant code that helped me sending data to the server. Hope it helps
var form = $('#add_message')[0]; // standard javascript object here
var formData = new FormData( $('#add_message')[0]);
$.ajax({
type: "POST",
url: base_url + "apps/messages/composeMessage",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(response){
// some action on success
},
error: function(response){
// some action on error
}
});