Jquery upload multifile just uploaded the first select file - javascript

I use this plugin to upload multifile fyneworks. My problem is like this :
- Select one or more e:g 2 files on browse button, then I get those files
- I clicked again, and choose a lot of file e/g 1 file, on preview I got three.
- But when uploaaded, I just got the two image which is the first select.
This is my code :
I have a div to display menu upload like this:
$(document).on("click", '#menu_container', function () {
var this_url = $(this).attr("href");
$.post(this_url, {}, function (data) {
$('#content').html(data);
$('#file').addClass("multi with-preview");
$('#file').MultiFile({
list: "#log",
max: 10,
accept: 'jpg|png|gif|jpeg',
STRING: {
file: '<p>$file</p>',
remove: '<button type="button" class="btn btn-sm btn-danger">Hapus </button>'
}
});
});
return false;
});
Now, this is the html page :
<?php echo form_open_multipart('', array('id' => 'upload', 'enctype' => "multipart/form-data")); ?>
<div class="form-group col-sm-12 ">
<label for="file">Upload Foto</label>
<input name="file[]" id="file" class=" btn" type="file" multiple >
<div class="col-sm-6" id="log"> </div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
<?php echo form_close(); ?>
I use ajax to submit this photo like this :
$('#upload').submit(function () {
$.blockUI();
var form = $('#upload');
var inputFile = $('input#file');
var filesToUpload = inputFile[0].files;
// make sure there is file(s) to upload
if (filesToUpload.length > 0) {
// provide the form data that would be sent to sever through ajax
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
$.ajax({
url: "<?php echo base_url('surveyor/c_surveyor/add_file_image/'); ?>/" + response.Nama_file + response.No_inspection,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (obj) {
$.unblockUI();
$(":file").val('');
$(":text").val('');
$("#comments").val('');
$(".MultiFile-label").empty();
$('#pilih_isotank').before('<div class="callout callout-success lead" id="div_error"><p id="pesan_error">Data Berhasil Terupload dengan Nomor : ' + response.No_inspection + '</p></div>');
$('#pilih_isotank').after('<div class="callout callout-success lead" id="div_error"><p id="pesan_error">Data Berhasil Terupload dengan Nomor : ' + response.No_inspection + '</p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html(obj.Message);
$('#div_error').fadeOut(7000);
$('input:file').MultiFile('reset');
console.log("Update succcess");
},
error: function () {
alert('Ada yang salah, press ctrl + r');
}
});
} else {
$('#file').after('<div class="callout callout-danger lead" id="div_error"><p id="pesan_error"></p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html("Please Choose your Photo...");
$('#div_error').fadeOut(7000);
$.unblockUI();
}
return false;
});
I have read on doc :there is event :
onFileAppend
afterFileAppend
onFileSelect
afterFileSelect
onFileRemove
afterFileRemove
What should I do. Any help it so appreciated.

Related

file not inser javascript by serialize

I am using Codeigniter and javaScript file upload and insert database but not responce so please check my code abd share valuable idea. share all code heare...view page form data , javascript code responce error and modals submit data code here.....
view
<form id="frm_submit" enctype="multipart/form-data">
<input type="file" name="reportfile" class="form-control">
<button type="submit" class="btn btn-info" name="submit"> Save</button>
</form>
javaScript
$("#frm_submit").on('submit', function (e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: $("#frm_submit").serialize()
}).always(function (response){
var r = (response.trim());
if(r !=0){
$(".success").show();
$(".danger").css("display","none");
setInterval('location.reload()',2000);
}else{
$(".danger").show();
$(".success").css("display","none");
}
});
});
models
public function vendors_upload_report_file()
{
$db2 = $this->load->database('bstdc',TRUE);
date_default_timezone_set('Asia/Kolkata');
$vendorsid = $this->session->userdata['vendors_data'][0]['vendor_id'];
$file_request_id = $this->input->post('file_department_id');
$file_request_id = $this->input->post('file_request_id');
$reportfile = $this->input->post('reportfile');
$today_date = date("Y-m-d");
if(!empty($reportfile)){
$filename = $_FILES['reportfile']['name'];
if (!empty($filename)){
$pic = $a.'-'.rand(5,10).time()."".$filename;
move_uploaded_file($_FILES['reportfile']['tmp_name'],'upload/files/'.$pic);
$report_pic_url = ''.base_url().'upload/files/'.$pic.'';
$db2->query('INSERT INTO bstdc_reports_file (request_id,sendor_type,sendor_id,reports_file,reports_file_url,created_date,act_status,del_status)
VALUES ("'.$file_request_id.'","Vendors","'.$vendorsid.'","'.$pic.'","'.$report_pic_url.'", "'.$today_date.'", "Y","N")');
return true;
}else{
return false;
}
}
}
Use FormData object to upload file
$("#frm_submit").on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: new FormData(this), // <== changed from $("#frm_submit").serialize()
}).always(function (response) {
var r = (response.trim());
if (r != 0) {
$(".success").show();
$(".danger").css("display", "none");
setInterval('location.reload()', 2000);
}
else {
$(".danger").show();
$(".success").css("display", "none");
}
});
});

Send file from AJAX and retreive from PHP

I have a form in which I retrieved the fields with ajax and send those as post to a PHP file. But one of the fields is a input type="file".
My question is as follow: how to properly send this file (an image) via ajax to the PHP file and read the file so I can upload it to a server.
Here's my code:
The form and fields
<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
<div class="response" id="response"></div>
<div class="custom-file">
<input type="hidden"
name="<?php echo ini_get("session.upload_progress.name"); ?>"
value="video_upload">
<input type="file" name="lien_video" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choisir le logo</label>
</div>
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'>0%</div>
</div>
...and some other stuffs
The script so far it's inside the same PHP file as the form
<script type="text/javascript">
$(document).ready(function () {
//upload data
$(document).on('click', '#enreg_ecole', function () {
let nom_ecole = $('#input-1').val();
let adresse = $('#input-2').val();
let nom_rep = $('#input-3').val();
let email_rep = $('#input-4').val();
let tel_rep = $('#input-5').val();
let poste = $('#input-6').val();
// let logo = $('#customFile').val();
let logo = document.getElementById("customFile").files[0];
var form = new FormData();
form.append('enreg_ecole', 1);
form.append('nom_ecole', nom_ecole);
form.append('adresse', adresse);
form.append('nom_rep', nom_rep);
form.append('email_rep', email_rep);
form.append('tel_rep', tel_rep);
form.append('poste', poste);
if(logo != null){
form.append('logo', logo);
}
$('#scroller').animate({scrollTop: 0}, 'fast');
var bar = $('#bar');
var percent = $('#percent');
$.ajax({
url: 'methods/enregistrer_ecole.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data:form,
enctype: 'multipart/form-data',
dataType: 'json',
beforeSubmit: function () {
document.getElementById("progress_div").style.display = "block";
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function (response) {
let status = response['status'];
let message = response['message'];
if (status === 'error') {
// window.alert(message);
document.getElementById("progress_div").style.display = "none";
document.getElementById("alert_div").style.display = "inline";
$('#alert_div').addClass('alert-danger');
$('#alert_title').html(status);
$('#alert_message').html(message +' ' +logo);
} else {
// window.alert(message);
document.getElementById("alert_div").style.display = "inline";
// $('#bar1').animate({width: "100%"}, 100);
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
$('#alert_div').addClass('alert-success');
$('#alert_title').html(status);
$('#alert_message').html(message);
}
},
// complete: function (xhr) {
//
// },
error: function (error, ajaxOptions, thrownError) {
// let error = JSON.parse(response);
// window.alert('Error happenned: ' + error);
// window.alert('Error happenned: ' + response.msg);
// var msg = $.parseJSON(error).msg;
window.alert(error);
window.alert(ajaxOptions);
window.alert(thrownError);
}
});
//window.alert('clicked');
});
});
</script>
I want to be able to do something like:
$target_file = $target_dir . basename($_FILES["lien_video"]["name"]);
----EDIT----
Okay, I tried some more codes and it looks like on my PHP file (enregistrer_ecole.php called from ajax), if I try to retrieve only the texts from the form, it's okay. If I try to retrieve only the file, it's okay. But trying to retrieve both the texts and the picture file (like $_POST['someText'] and $_POST['someFile']['tmp_name'] it throws an error.
Does anyone know a way to do this properly? Like get the texts first and then get the file. I don't know.
HTML
<div class="container">
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'>
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
PHP
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
$uploadOk = 0;
}
if($uploadOk == 0){
echo 0;
}else{
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
}else{
echo 0;
}
}
One of the form attribute is missing in your HTML and that is enctype
<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
</form>
and there can be one improvement: instead of writing each input field appended to form data object, you can write single line.
you can replace all these lines
var form = new FormData();
form.append('enreg_ecole', 1);
form.append('nom_ecole', nom_ecole);
form.append('adresse', adresse);
into a single line as below:
var form = new FormData($("form")[0]);

Uploading Image to database in php & ajax

I am trying to upload an image to database from html page in a form in a modal through php & ajax,but it doesn't work i don't know why,anyone can help me?
HTML Page
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-4">
<label class="Modallabel">Photo:</label>
</div>
<div class="col-sm-8">
<div class="input-group input-group-sm" style="margin-top: -5px;">
<input type="file" id="fileUpload" name="fileUpload" style="color: #ffffff;"/>
</div><br>
</div>
</div>
</form>
<button type="button" class="btn btn-success btn-md" style="margin:0;width: 75px;" onclick="AddNewCustomer()">Add</button>
Javascript Function
function AddNewCustomer()
{
//Image upload
$(document).ready(function()
{
$(document).on('change', '#fileUpload', function() //NOT WORKING HERE
{
var property = document.getElementById("fileUpload").files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if (jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("invalid Image File");
}
var image_size = property.size;
if(image_size > 2000000)
{
alert("Image File Size is very big");
}
else
{
var form_data = new FormData();
form_data.append("fileUpload", property);
$.ajax
({
type:"POST",
url:"addNewCustomer.php",
processData: false,
cache: false,
contentType: false,
data:
{
'form_data':form_data
},
success: function(data){
if (data == "Success!")
{
sweetAlert("Data entered successfully!");
}
else if(data == "Exist")
{
sweetAlert("","Customer already exists!","error");
return false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
})
}
})
})
}
change event would be attached after click at <button> at onclick="AddNewCustomer().
You can remove AddNewCustomer function and call change on #fileUpload element at click of .btn element.
$(document).ready(function() {
$(document).on('change', '#fileUpload', function() {//do stuff})
$(".btn").on("click", function() {
$("#fileUpload").trigger("change");
});
});
You want to upload the image immediately after it's chosen, but you only run the function when the 'Add' button is clicked.
You need to take your change code out of the function, or invoke the function when the page is loaded to add the listeners to the form.

jquery AJAX Post not working Codeigniter

I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..
HTML :
<form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">
<?php foreach($data as $rod)
$tahun = $rod->id_smt;
$jurusan = $rod->id_sms;
?>
<div id="form-tahun" class="form-group">
<input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">
</div>
<div id="form-jurusan" class="form-group">
<input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">
</div>
Sedang Mengunggah :
<div id="statmhs"> </div>
<div id="statidmhs"> </div>
<div id="statdsnpt"> </div>
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
JS :
$(document).ready(function() {
$('#unggahsemua').submit(function(event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun' : $('input[name=tahun]').val(),
'jurusan' : $('input[name=jurusan]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
.fail(function(data) {
console.log(data);
});
event.preventDefault();
});
});
You have errors in your Javascript code..
You missed the closing brackets before the .fail method. Also you had an extra comma after the last entry of your formData object
Try changing to this:
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
You have to stop default execution of form submit as you have to do it with ajax.
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
event.preventDefault() //<------- Add this line
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
});
});
if you use form action="" method="POST" name="" role="form", make sure in config.php change $config['csrf_protection'] = TRUE; to FALSE.
But, if you want to set it TRUE you must use form_open()

Show a progress on multiple file upload Jquery/Ajax

I have upload form that allows users to upload multiple files. I decided that a progress bar would be good if the files are quite large. Below is my source code. I am new to jquery normally I would just php but I find that ajax is more user friendly.
<div id="new_upload">
<div class="close_btn"></div>
<div id="uploads"></div>
<form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
<fieldset><legend>Upload an image or video</legend>
<input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
</fieldset>
<div class="bar">
<div class="bar_fill" id="pb">
<div class="bar_fill_text" id="pt"></div>
</div>
</div>
</form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%') //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
console.log('ajax start');
}
function afterSuccess(data){
console.log(data);
}
$(document).ready(function(e) {
$('#upload_file').submit(function(event){
event.preventDefault();
var filedata = document.getElementById("file");
formdata = new FormData();
var i = 0, len = filedata.files.length, file;
for (i; i < len; i++) {
file = filedata.files[i];
formdata.append("file[]", file);
}
formdata.append("json",true);
$.ajax({
url: "global.func/file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
resetForm: true
});
});
});
</script>
The image upload works fine, the array send to ajax but the progress bar doesn't move. In fact the console.log for the two functions called need to produce this don't appear either. Is there a correct way to call the functions in my ajax request that would get this progress bar to work.
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
NOTE that this function 'success: afterSuccess' is working as the console is displaying my data.
This is your HTML form
<form method="post" action="uploadImages.php" name ='photo' id='imageuploadform' enctype="multipart/form-data">
<input hidden="true" id="fileupload" type="file" name="image[]" multiple >
<div id ="divleft">
<button id="btnupload"></button>
</div>
</form>
This is your JQuery and ajax.
By default the fileInput is hidden.
Upload Button clicked
$("#btnupload").click(function(e) {
$("#fileupload").click();
e.preventDefault();
});
$('#fileupload').change(function (e) {
$("#imageuploadform").submit();
e.preventDefault();
});
$('#imageuploadform').submit(function(e) {
var formData = new FormData(this);
$.ajax({
type:'POST',
url: 'ajax/uploadImages',
data:formData,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log(data);
alert('data returned successfully');
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
});
function progress(e){
if(e.lengthComputable){
var max = e.total;
var current = e.loaded;
var Percentage = (current * 100)/max;
console.log(Percentage);
if(Percentage >= 100)
{
// process completed
}
}
}
Your php code looks like this
<?php
header('Content-Type: application/json');
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 30000 * 1024; // max file size in bytes
$json = array();
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
for($i=0;$i<count($_FILES['image']['tmp_name']);$i++)
{
$path="image/uploads/photos/";
if(is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$uid = uniqid();
$date = date('Y-m-d-H-i-s');
$path = $path ."image_" .$date. '_' . $uid . "." .$ext;
$returnJson[]= array("filepath"=>$path);
$filename = "image_" . $date . "_" .$uid . "." . $ext;
$this->createthumb($i,$filename);
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
//$status = 'Image successfully uploaded!';
//perform sql updates here
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
}
else {
$status = 'Bad request!';
}
echo json_encode($json);
?>
You must use a custom XMLHttpRequest to do this with AJAX and jQuery. There's an example here: How can I upload files asynchronously?

Categories