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);
},
});
}
Related
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
Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});
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
}
});
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.
How can I create the callback after a file is upload on the server?
I want to upload a file on a server after a JS function call.
I want to call the function addDownload and after this function is complete, then call the next javascript function. How can I do this?
I have a following source code:
HTML:
<form id="imageform" method="post" enctype="multipart/form-data" action="actions/downloadsadd.php">
<strong>File: </strong><input name="photoimg" id="photoimg" style="width: 100px;" type="file" />
Select Image: <br />
<div id="divPreview"></div>
</form>
Javascript:
addDownload: function ()
{
$("#divPreview").html('');
$("#divPreview").html('<img src="Images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#divPreview'
}).submit();
},
PHP - downloads.php:
public function addDownloads() {
$db = new DB();
$db->connect();
$path = "../../images/upload/files/";
$valid_formats = array("php", "phtml", "php3", "php4", "js", "shtml", "pl", "py", "html", "exe", "bat", "htm", "sql");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if (strlen($name)) {
list($txt, $ext) = explode(".", $name);
if (!in_array($ext, $valid_formats)) {
if ($size < (1024 * 1024)) { // Image size max 1 MB
$actual_image_name = time() . "." . $ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if (move_uploaded_file($tmp, $path . $actual_image_name)) {
$arr = array(
'file' => $actual_image_name
);
dibi::query('INSERT INTO [downloads]', $arr);
echo "FILE:" .$actual_image_name;
}
else
echo "Failed upload!";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
}
}
Just guessing, but your code seems use the jQuery form plugin:
$("#imageform").ajaxForm(...);
The plugin allows you to add a callback function using the success option. This function will be invoked when the AJAX request (i.e. all the code in the PHP file you're calling) has finished successfully.
$("#imageform").ajaxForm({
target: '#divPreview',
data: {
var1: $("#inputText").val() //assuming #inputText is a text field
},
success: function() {
alert("Callback!");
}
}).submit();
See the documentation for further reference.
I did like this to upload avatar.
<script type="text/javascript">
$('input[id=lefile]').change(function() {
$('#photoCover').val($(this).val());
});
function doUpload(){
//Use FormData to get files in form.
var formData = new FormData($("#myform")[0]);
$.ajax({
url: $('#myform').attr('action'),
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="avatar-content">
<form id="myform" action="http://www.example.com/editor/" method=post enctype=multipart/form-data>
<input id="lefile" type="file" name="file" style="display:none">
<div class="input-append">
<input id="photoCover" type="text" class="form-control" style="height:34px; width: 54%; display: inline-block;" onclick="$('input[id=lefile]').click();">
<div class="btn btn-primary btn-file" onclick="doUpload()">
<i class="fa fa-upload"></i> Upload
</div>
</div>
</form>
</div>