Hi I would like to seek help on how can I convert my regular Multiple Select Form Upload using AJAX to a Dropzone?
Below is my existing code:
<form name="uploadForm" id="uploadForm" method="POST" enctype="multipart/form-data">
<select class="form-control" id="templateName" name="templateName">
<option value="">-Select Template-</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="file" class="custom-file-input" name="xml_file[]" id="xml_file" multiple>
<button type="button" id="upload">Upload</button>
</form>
<script>
$("#upload").on("click", function(){
formData = new FormData($("form[name='uploadForm']")[0]);
$.ajax({
url: 'ajax-file-upload',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
</script>
This is what I am trying to do
<script>
Dropzone.autoDiscover = false;
/* Dropzone Configuration */
var myDropzone = new Dropzone("#uploadForm", {
autoProcessQueue: false,
parallelUploads: 50 // Number of files process at a time (default 2)
});
$("#upload").on("click", function(){
formData = new FormData($("form[name='uploadForm']")[0]);
$.ajax({
url: 'ajax-file-upload',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
</script>
However it only returns me formdata for the select option tag,
I know myDropzone.files can return me the files to be uploaded but how do I make it the same exact formdata that I passed on originally. Because I need to access the xml_file data on the backend.
I already come up with the solution,
(1) first I need to retain the <input type="file" class="custom-file-input" name="xml_file[]" id="xml_file" multiple> , you may hide it if you totally want to upload just by dropping the files, otherwise leave it visible.
(2) Upload Clicking Upload Button, I will need to set and update the value of the formData. To update my formData I need to append input name xml_file[]
with
.dropzone.getAcceptedFiles(). This is how we access dropzone accepted files, loop into this array to see all the accepted files.
See below for reference, there's still a lot of room for improvement, I will just leave it like this for now.
<script>
Dropzone.autoDiscover = false;
/* Dropzone Configuration */
var myDropzone = new Dropzone("#uploadForm", {
autoProcessQueue: false,
parallelUploads: 50 // Number of files process at a time (default 2)
});
$("#upload").on("click", function(){
formData = new FormData($("form[name='uploadForm']")[0]);
$.each($("form[name='uploadForm']")[0].dropzone.getAcceptedFiles(),
function(a,b){
formData.append('xml_file[]', $("form[name='uploadForm']")[0].dropzone.getAcceptedFiles()[a]);
});
$.ajax({
url: 'ajax-file-upload',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
</script>
Related
This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
I am trying to send the form data to PHP with AJAX but when dumping data on PHP page it is returning null values.
Actually, I want a program where I can upload an image than in pop up crop it and then save the cropped image in the database.
My code is given below:
$('#fileinput').on('change', function() {
var formD = new FormData();
var file = $('#fileinput')[0].files[0];
// var nfile = file.serializeArray();
// console.log(file);
formD.append('file', file);
formD.append("clientID", 2993);
console.log(formD);
$.ajax({
url: 'croped.php',
type: 'POST',
data: {
'ff': formD
},
processData: false,
contentType: true,
// dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" id="fileinput" />
<input type="submit" name="upld" id="upldbtn" />
</form>
croped.php
<?php
var_dump($_POST);
echo "ll";
?>
Please let me know what I am missing or doing wrong.
Try this, it works for me :)
contentType: false,
data: formD,
For example
$.ajax({
url: "croped.php",
type: "POST",
data: formD,
processData: false,
contentType: false,
// dataType: 'json',
success: function (data) {
console.log(data);
},
});
For the php code
<?php
echo "<pre>";
print_r($_FILES);
<form action = "" method = "POST" enctype = "multipart/form-data"
id="formdata">
<input type = "file" name = "image" id="fileinput" />
<input type = "submit" name="upld" id="upldbtn" />
</form>
$("#formdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
I generated the next form in jQuery:
$('.content').append('
<form name="make_new_model_release" enctype="multipart/form-data">
<input data-validate="validate" type="text" name="new_model_release_title" placeholder="Enter new model release title" />
<input type="file" name="newModelReleaseFile" id="newModelReleaseFile" />
<input type="submit" value="Create new model release" />
</form>');
Server side simple:
var_dump($_FILES);
AJAX code:
var data = form.serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: formurl,
data: data,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
after submitting the $_FILES array is empty.
I checked php.ini
file_uploads=On |
upload_max_filesize=128M | post_max_size=128M
Temp folder is allowed for read and write
I tried to make data: new FormData(formId) - nothing changed, $_FILES array is empty.
If you used jQuery('#dailyActivity').serialize(),
It it is not working for <input type'file'>
Have look at this jsFiddle Does not works
and this one .serialize()
Data from file select elements is not serialized.
Have look at this https://stackoverflow.com/a/8758614/3425489
In you case try this
To send <input type'file'> you may want to try this
var formData = new FormData($('form')[0]);
or specify exact data for formdata
var formData = new FormData();
// Append your other Data
formData.append('newModelReleaseFile', $('input[type=file]')[0].files[0]);
And you ajax call will be
$.ajax({
type: 'POST',
url: formurl,
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
Follow this way for upload an image, In this way you don't want HTML form.
Add this code to your mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
Then add this for upload.php
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#upload_doc").on("change", function() {
$("#imageUploadForm").submit();
});
});
</script>
From your comment,
actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.
If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
So your jQuery should be like this:
if(currentIndex == 0){
event.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response) {
console.log(response);
}
});
}
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});