jQuery File Upload done function - javascript

I've modified the example code provided on jQuery File Upload's Wiki My scripting works for the add callback but not the done callback. The server is getting the post correctly and returning a JSON response.
I've noticed in the source code some of the callbacks are commented out. I'm not sure if I should uncomment them or not. Or use the callback fileuploaddone But removing the comment did not work.
Not sure if i'm doing this correctly. I'd like the server to return me a JSON object describing the image I just uploaded so the next step of my form can link the image with a backbone.js model.
<form id="uploadform">
<input id="fileupload" type="file" name="imagefile" data-url="imagefiles" multiple>
<button type="#" class="btn btn-primary uploadfile" style="display: none">Upload</button>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
</form>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
data.context = $('.uploadfile').css('display','none')
utils.addValidationSuccess('Added file: ' + data.jqXHR.name);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
},
add: function (e, data) {
console.log('added');
data.context = $('.uploadfile')
.css('display','block')
.click(function () {
utils.showAlert('Uploading','...', 'alert-warning');
data.submit();
});
}
});
});
</script>

What got things working was using jquery.ajax 's apparently native callback on submit, adjusted code shown below.
<div class="row-fluid">
<form id="uploadform">
<input id="fileupload" type="file" name="imagefile" data-url="imagefiles" multiple>
<button type="#" class="btn btn-primary uploadfile" style="display: none">Upload</button>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
</form>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
},
add: function (e, data) {
console.log('added');
data.context = $('.uploadfile')
.css('display','block')
.click(function () {
utils.showAlert('Uploading','...', 'alert-warning');
var jqXHR = data.submit()
.success(function (result, textStatus, jqXHR) {
console.log('Done');
console.log('e:' + e);
console.log('results:' + result );
console.log('results.id:' + result.id );
console.log('textStatus:' + textStatus );
console.log('jqXHR:' + jqXHR );
data.context = $('.uploadfile').css('display','none')
utils.showAlert('Success','the file uploaded successfully','alert-success');
// utils.addValidationSuccess('Added file: ' + data.jqXHR.name);
})
.error(function (jqXHR, textStatus, errorThrown){
utils.showAlert('Error','...', 'alert-error');
});
});
}
});
});
</script>
</div>

I had the same problem with this code.
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
alert("done");
}
});
});
Just with not setting the dataType, the done callback is now executed ...
Code below just work ...
$(function () {
$('#fileupload').fileupload({
done: function (e, data) {
alert("done");
}
});
});
The server return some json.

Related

File Upload Progress Bar with Multiple and Different Inputs(MVC)

I searched the internet and found this JavaScript and jQuery template for a file upload progress bar that works 100% fine(given the fact that you only use one form input).
My situation is that I need to pass one file and 4 other inputs like text and select to a Controller Action. The action works fine. My problem is to pass all these values through ajax to the Action whilst maintaining the progress bar functionality.
Action Parameters
[HttpPost]
public ActionResult Add_Attachment_to_Process(int id, int Department_id, HttpPostedFileBase Attachment, string sel_checkTask, string cbx_checkTask = null)
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" action="/Processes/Add_Attachment_to_Process" id="myform">
<input type="file" id="media" name="file" />
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" aria-label="Checkbox for following text input" id="cbx_checkTask" name="cbx_checkTask">
<span id="span_checkTask">Link Task</span>
</div>
</div>
<select class="form-control" id="sel_checkTask" name="sel_checkTask" style="width : 700px;" disabled>
#foreach (var t in Model.User_Tasks)
{
<option value="#t.Task_Discription">#t.Task_Discription - #t.Key_Terms</option>
}
</select>
</div>
<input id="id" name="id" value="#ViewBag.process_id " />
<input id="Department_id" name="Department_id" value="#ViewBag.Department_id" />
<input type="submit" />
</form>
<div class="progress" style="width:40%">
<div id="uploadprogressbar" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
JavaScript
$(document).ready(function () {
$("#myform").on('submit', function (event) {
event.preventDefault();
var formData = new FormData($("#myform")[0]);
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
console.log('Bytes Loaded: ' + e.loaded);
console.log('Total Size: ' + e.total);
console.log('Percentage Uploaded: ' + ((e.loaded / e.total) * 100) + '%');
var percent = Math.round((e.loaded / e.total) * 100);
$("#uploadprogressbar").html(percent + '%');
$("#uploadprogressbar").width(percent + '%');
}
});
return xhr;
},
type: 'POST',
url: '/Processes/Add_Attachment_to_Process',
data: formData,
processData: false,
contentType: false,
success: function () {
alert('File Uploaded');
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMessage);
}
});
});
});
AS per the discussion above, try this sort of pattern to better see what values are not being sent
let f = new FormData();
f.append('id', getYouFormValue("id"));
f.append('sel_checkTask', getYouFormValue("sel_checkTask"));
f.append('cbx_checkTask ', getYouFormValue("cbx_checkTask "));
if (form.File) {
f.append('File', getYouFormValue("file"));
}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: f
}
return fetch(`/Processes/Add_Attachment_to_Process`, requestOptions)
.then(handleResponse)
.then(result => {
//do stuff
});
function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);
if (!response.ok) {
if (response.status === 401) {
console.log('not logged in')
}
const error = (data && data.message) || data.title || response.statusText;
return Promise.reject(error);
}
return data;
});
}
function getYouFormValue(element){
let val = document.getElementById(element);
if(!val){
console.log('empty value');
return null;
}
return val;
}

Add a progress bar to ajax upload

I have the following code...
$('#submitForm, #error').fadeOut("slow", function() {
$('#submission_div').html("<div id='pleaseWait'>Please Wait...</div> ");
});
var formData = $('#comm_planner').submit(function(e){
return;
});
var formData = new FormData(formData[0]);
$.ajax({
url: 'process.php',
type: 'post',
data: formData,
success: function(data) {
$('#main').fadeOut('slow', function() {
$(this).html(data).fadeIn('fast');
});
},
error: function(jqXHR, textStatus, errorThrown) {
$('#main').fadeOut('slow', function() {
$(this).html(error).fadeIn('fast');
});
},
cache: false,
contentType: false,
processData: false
});
It uploads x number of files perfectly with no issues but I'd like to add a progress bar for the total amount of files being uploaded...the user could have anywhere from 0 to no set limit of files chosen for upload. So I'd like it to look at all of the files and display one upload bar for the total amount being uploaded.
Thanks in advance for any help!
For that, there are a lot of jquery plugins but i am using dropzone.js
Jquery Code
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#statusToGet');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
HTML Code
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="statusToGet"></div>

jquery file upload basic plus mutiple file upload

I am using basic plus of jquery file upload, and i am trying to have one upload button to upload multiple files at same time but its current showing multiple upload buttons if i select multiple files, you can see try it online at here
HTML Code
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
JS Code
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Its working but shows multiple upload buttons if i select multiple files to upload but i want to have one upload button which can process all uploaded files at same time. Thanks for your help.

How do I write the AJAX to post data

Fiddle
I am trying to learn AJAX from a tutorial.
I am able to grab the data I want and populate it in the DOM pretty easily.
What I'm struggling with is using 'POST' to edit it.
I created a simple page that lists 'friends' and 'ages' that pulls that data from here
http://rest.learncode.academy/api/learncode/friends
The names and ages populate correctly, but the code I'm writing to 'POST' to it is not.
Here is my javascript
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/learncode/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
</script>
HTML
<div class="large-12 columns" id="ajaxContainer">
<h1>
AJAX Container
</h1>
<h3>
Friends
</h3>
<ul id="friends">
</ul>
<h3>Add a friend</h3>
<p>
Name:
<input type="text" id="name" />
</p>
<p>
Age:
<input type="text" id="age" />
</p>
<button id="add-order"> submit</button>
</div>
I am guessing as to what you actually want, but it seems that you want the page to populate with whatever friends are currently in the database on first load, and then when you click add-order button, it adds new friends and updates your list. The first thing is that you are trying to POST to the learncode name, which you can't do. Change where it says "yourname" in the URLs below to something else. Here is what you should do:
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
$.ajax({
type: 'POST',
data: {"id":3, "age": $age.val(), "name":$name.val()},
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function () {
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
$friends.html("");
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +'
</li>');
})
},
error: function () {
alert("error loading data");
}
});
},
error: function () {
alert("error loading data");
}
});
});
});
</script>
See the part that says
type : "GET"
-?-
change it to
type : "POST"
Then, the url parameter is what you are POSTing to-
And you are not actually sending any data -!
So, try this:
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'POST',
url: 'http://yourWebsite.com/someScriptToHandleThePost.php',
data: [{"id":1,"name":"Will","age":33},{"id":2,"name":"Laura","age":27}],
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
Then, you're going to need a PHP script to handle the POSTed data and return a response, which gets passed in the data param in success:function(data){}
start out with something simple, like this:
<?php
print_r($_POST);
?>
and change your success function to:
success: function(data) {
$("body").append("<pre>"+data+"</pre>");
}
and that should get you on the right track....

Parsing a JSON response after a file upload with jquery

I have written a small script using jquery to upload a file to a server. The file is uploaded successfully and the done: event is called with no problems, but I am having issues to process the answer. This is my script:
<input id="fileupload" type="file" name="carPicture" accept="image/*" multiple>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/vendor/jquery.ui.widget.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/jquery.iframe-transport.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/jquery.fileupload.js")" type="text/javascript"></script>
<script>
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = "uploadCarPicture";
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
fail: function (e, data) {
alert("File exists");
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
I am having two problems:
the variable data seems to be empty since the loop below doesn't run even once.
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
The answer is a JSON document with the following format: {"e":0} where "e" is an error code. "e" could return many different values and I would like to be able to find out the real response and not always assume 0.
Any idea?
I have solved it. I've made a small change in the java script like this:
done: function (e, data) {
$.each(data.files, function (index, file) {
$('<p/>').text(file.name);
});
},
And I have changed the json that the server was responding to this format:
{
files:
[
{
error: 0,
name: "thumb2.jpg",
}
]
}

Categories

Resources