I am using this plugin for bootstrap to upload files which is stored in a form with submit button
http://plugins.krajee.com/file-input/
My question is -
a) is there a method or something to either check if there are files in the dropZone that are still not uploaded and notify a user after he submits a form that he didn't uploaded the files
b) is there a method that will trigger the upload when the submit button is fired?
Now it looks like this - if I submit my form it wont upload the files and just pass the form, I have to manually click upload files then submit the form
Maybe some of you came across this issue cause I am not able to figure it out myself due to poor documentation.
I found a work around for this issue.
<input id="input-photos" name="Photos" multiple type="file" class="file-loading">
Define a global variable in Javascript:
var formData = new FormData();
Append the selected files to formData on filePreUpload action.
$('#input-photos').on('filebatchpreupload', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
$.each(files, function (key, value) {
if(value != null){
formData.append("Photos", value, value.name);
}
}); });
On form submission append all form fields and post the form through ajax.
$('#yourForm').submit(function() {
$('#input-photos').fileinput('upload');
var model_data = $("#yourForm").serializeArray();
$.each(model_data,function(key,input){
formData.append(input.name,input.value);
});
$.ajax({
url: "#Url.Action("Save", "Home")",
type: "POST",
datatype: "json",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: (function (result){
window.location.href = '#Url.Action("Index", "Home")';
}),
error: function (xhr) {
alert("Error: " + xhr.statusText);
}
});
return false;
});
Validation of required property for form based upload (non ajax) scenario, which will enforce files to be selected and required before upload. This scenario includes custom form submit and reset buttons for upload (and default upload and remove buttons are hidden). The upload will force a file to be selected and required - else a validation error as set in msgRequired will be shown.
Try it:-
https://plugins.krajee.com/file-count-validation-demo#required-non-ajax-1
Related
I'm struggling trying to upload two files to a php script and let the page download a new merged file without redirecting to a second page.
I don't want to cache any file on the server, because they could be large (2MB) binary files.
looking at this question:
Download a file by jQuery.Ajax
it seems that the jQuery File Upload plugin cannot handle uploads. There is an example posting a text. But it seems that file uploads don't pass through when the data gets serialized.
$(document).on("submit", "form.fileDownloadForm", function (e) {
$.fileDownload($(this).prop('action'), {
preparingMessageHtml: "We are preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again.",
httpMethod: "POST",
data: $(this).serialize()
});
e.preventDefault(); //otherwise a normal form submit would occur
});
You can just add both files to a formData object, upload them with ajax and return the file
Something like
<form class="fileDownloadForm" method="POST">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit>
</form>
and then
$(document).on("submit", "form.fileDownloadForm", function (e) {
e.preventDefault();
$.ajax({
url : $(this).prop('action'),
type : "POST",
data : new FormData(this), // both inputs or "multiple" etc in same form
processData : false, // tell jQuery not to process the data
contentType : false // tell jQuery not to set contentType
}).done(function( data ) {
// return concatted file here as data from the server
});
}
and return it
<?php
echo file_get_contents($_FILES['file1']) . file_get_contents($_FILES['file2']);
?>
You can use FormData() instance to post files to server using $.post() at change event of <input type="file">, at .then() offer download of merged file to user
var fd = new FormData();
var n = 0;
for (let file of e.target.files) {
fd.append("files[" + n++ +"]", file);
}
$.post("/path/to/server", {files:fd})
.then(function(data) {
// offer download of `data` here
})
I have a form on my website that the user needs to fill in order to generate a PDF file. If there are errors in the form, the server will respond with a json object with the list of errors, otherwise will respond with the PDF file (as a string). I'm trying to display that PDF file inside a Magnific-Popup (https://www.npmjs.com/package/magnific-popup).
$('.preview-button').on('click', function (e) {
event.preventDefault();
var theLink = $(this);
var formElement = theLink.closest("form");
$.ajax({
url: theLink.attr('href'),
method: 'GET',
data: formElement.serialize(),
success: function (response, textStatus, jqXHR) {
var contentType = jqXHR.getResponseHeader("content-type") || "";
if(contentType.indexOf('pdf') > -1){
// How can I tell to magnific popup to display the response as PDF?
$.magnificPopup.open({
// tell magnific popup to use the response...
type: 'iframe',
closeOnBgClick: false
});
}
else{
if (response.hasOwnProperty('errors')){
// Form has error, show them
alert(response.errors);
}
}
}
});
});
This might be useful for someone with the same problem: Instead of sending the pdf file as a response, I decided to generate a temporary pdf file in the server and send the path to that file as response. Then we can tell to magnificPopup to display it inside an iframe.
I have a form containing an input of type file that can accept multiple files(images) as shown below:
<input type="file" id="fileupload" name="fileupload[]" multiple />
Once a user selects an image or multiple images they are added dynamically to the website and also the user can remove one or all of them if he wants to.
Is there a way I can update which files are chosen from the input element to send to php script?
If not how can I send only images the user chooses? I mean I can put what the user chose in another array in JavaScript but how can I send them to php script?
Edited
In more details for example when the user chooses three image files there is JavaScript code i use that appends them into screen as images and the user is given the option to remove one or all of them by clicking on them. So my problem is if the user for example removed one of the images how can I send only the other two images into the php script?
I am not looking for complete code. I am just looking for a hint on how to accomplish it.
I've understood what you want.
Combine Ajax with formData to get that.
$(document).ready(function(){
$("form#data").submit(function(){
// create your filtred list of files from your file input
var data = {};
$.each($('#fileupload')[0].files, function(i, file) {
// Keep only the files that the user has selected
if ( i % 2 == 0){ // <--- CHANGE THIS
data['file-'+i] = file;
}
});
// create a FormData (to send files with AJAX)
var formData = new FormData();
for (var key in data) {
formData.append(key, data[key]);
}
// send that formData
php_script_url = "your_script.php"
$.ajax({
url: php_script_url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Don't forget to include jQuery before this script
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
What I need to do:
I have an upload form with a file input and hidden text inputs. The user uploads an image, the image gets manipulated and then sent to remote server for processing which takes a few seconds, then the remote server sends the finalized images back to the home server where they are saved in a new folder. JavaScript needs to reach these new images to do further data processing on the newly saved images (which also takes a second). Only after JavaScript has done its thing and updated the form's input variables can the form be submitted.
Right now I've got all of the separate pieces working, but executing everything in one click has proven to be a challenge.
My code for uploading the images:
PHP:
if(isset($_POST['submit'])){
//do image manipulation and save new files using PHP
}
JS:
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
}
PHP again:
if(isset($_POST['input_variables'])){
//send these variables to SQL database
}
I know trying to use JavaScript to get the newly saved images isn't an ideal approach, but the framework that I'm using is only available in JavaScript. Is this even possible with one click?
You can do this:
In your HTML, add data-processed="false" to your form like this:
<form action="upload.php" method="post" name="q_data" data-processed="false" enctype="multipart/form-data">
In your jQuery call this to submit the images via ajax:
$("form[name='q_data']").submit(function(e) {
var $this = $(this);
var processed = $this.data('processed')
if (processed == false) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: formData ,
async: false,
success: function(msg) {
//alert(msg);
if (msg !== 'success') {
$this.data('processed', true)
furtherProcessing();
}
},
cache: false,
contentType: false,
processData: false
});
}
});
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
$("form[name='q_data']").submit();
}
In some-page.php do this:
if(isset($_POST['some-image-input-name'])){
//do image manipulation and save new files using PHP
return 'success'
}
However, if it were me, I'd have that first ajax call (that saves the images) simply return the urls for the saved images, then there is no need for a second ajax call to retrieve them which I assume is what you are doing now
I am using Malsup's jQuery Form Plugin to upload files asynchronously, as per this question.
It works great for uploading files, but I'm interested in sending additional data along with the file (such as the username of the person uploading it.
Is there some way to add this additional data?
Here's the current code that works for uploading files:
(Assume a standard <input type=file/> in an HTML form with id=upload)
// site/js/app.js
var app = app || {};
(function($){
})(jQuery);
// prepare the form when the DOM is ready
$(document).ready(function() {
var options =
{
url: 'http://localhost:3000/file_upload',
dataType: 'json',
success: function(response, statusText, xhr, form)
{
alert('success!');
};
$("#upload").ajaxForm(options);
});
After playing around with it for a few days, I found the answer.
Simply put, there is an 'options' property of "data" which contains everything that will be sent to the server. When using the Form is set to enctype="multipart/form-data", this grabs only the file type inputs, ignoring everything else.
However, if you can access the values of the other input fields (sounds like a job for $!), you can manually add the extra data with a specific callback function.
This would make your jQuery code look like this:
// site/js/app.js
var app = app || {};
(function($){
})(jQuery);
/*
$('#upload').submit(function()
{
alert('Handler for .submit() called.');
return false;
})*/
// prepare the form when the DOM is ready
$(document).ready(function() {
var options =
{
url: 'http://localhost:3000/file_upload',
dataType: 'json',
beforeSubmit: function(arr, $form, options)
{
//add additional data that is going to be submit
//for example
arr.push({ 'name': 'username',
'value': 'Jarrod Dixon'});
},
};
$("#upload").ajaxForm(options);
});
In my case, I'm using express.js as my webserver, which means the additional data is available in app.post's response's 'param' property as req.param('username').
i.e.,
app.post('/file_upload', function(req, res) {
//see if we got the username
console.log('name = '+ req.param('username'));
//Jarrod Dixon
});
Hope this helps save someone else fruitless hours of searching!