I wanted a jQuery multi file uploader with process bar. Thats why I went to this url. In this there is one option called basic. I just downloaded all the files and I used only the basic.html file. With basic.html files code I can easily upload files. But I want some restriction so that user will only upload some kind of files like png,jpg and gif only. So to use restriction in upload I checked for documentation and I got this link.
So I mixed all the codes like this
<div class="container">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Select 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>
<br>
</div>
<script>
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === '' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
options: {
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
processQueue: [
action: 'validate',
acceptFileTypes: '#',
disabled: '#disableValidation'
]
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
file = data.files[data.index],
if (!options.acceptFileTypes.test(file.type)) {
file.error = 'Invalid file type.';
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
But here I can't upload any files also I can't get restriction in upload. After all this codes in my firefox console tab I got an error like
SyntaxError: missing ] after element list
action: 'validate',
Can someone kindly tell me why this error is here? How to solve this? Any help and suggestions will be really appreciable. Thanks..
Missing a comma there between literal objects, after processActions
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === '' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
options: {
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
processQueue: [
action: 'validate',
acceptFileTypes: '#',
disabled: '#disableValidation'
],
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
file = data.files[data.index],
if (!options.acceptFileTypes.test(file.type)) {
file.error = 'Invalid file type.';
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
} // end of options
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Related
I am trying to use jquery( v. 1.11.3 )ajax, in conjunction with jquery.validate 1.15 to upload a form that includes input type file. You can see from the js comment lines some of everything I have tried. With each of the variations the php script returns "no image file". Of course, if I remove the jquery script, the form submits fine with accompanying page refresh. I really wanted to eliminate the page refresh for a better UX but I am having no luck getting this to work. If someone could help me fix my code, I'd really appreciate it. Please Note: I have researched numerous examples of jquery ajax .post but these examples are not helping me as those code structures don't work with Jquery.Validate plugin. I also found this answer here: File Upload PHP AJAX but as you can see from my code comments, I have tired this with no luck.
I must be missing something.
Heading ##The html and js:
<!DOCTYPE html>
<html>
<body>
<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
<input type="file" name="itemImg" id="itemImg" />
<label>Name</label>
<input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />
<input type="submit" value="Upload Form" name="submit">
<div>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
error.insertAfter(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
$('#addItemsForm').validate({ // initialize the plugin
debug: true,
submitHandler: function(){
//var formData = $('#addItemsForm').serialize();
//var data = new FormData($('#addItemsForm'));
//var form = $('form')[0];
//var formData = new FormData(form);
//console.log(addform);
var frmData = new FormData($(this)[0]);
$.ajax({
url: "imgUploadTest.php",
data: frmData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done( function(res, jqXHR, textStatus) {
console.log(res);
//$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
//$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
//$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
})
.fail( function (res, jqXHR, textStatus, errorThrown){
alert("failed! " + jqXHR, textStatus);
});
return false;
} // submitHandler
}); // validate
}); // doc ready
</script>
</body>
</html>
Heading ##The PHP:
<?php
include 'imguploader.class.php';
// FUNCTIONS
function imagehandler($item_attr_ID) {
$imgId = $item_attr_ID;
$img = new imgUploader($_FILES['itemImg']);
$time = time();
$thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100); // change these numbers for display
$small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400); // change these numbers for display
//$full = $img->upload_unscaled('mobileApp/uploads/', $time);
if($thumb && $small){ // && $full
return array($thumb, $small);
/* TO SHOW IMAGE
echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
*/
} else {
echo ( 'ERROR! '.$img->getError() ); // --> error code 011.1
}
} // end imagehandler()
// Processes
if (!empty( $_FILES["itemImg"]) ){
$item_attr_ID = "jPlayerandtheGirls_8_1456";
list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
if ($item_img_thumb && $item_img_small){
$r["thumb"] = $item_img_thumb;
$r["small"] = $item_img_small;
} else {
$r["thumb"] = "No Thumb";
$r["small"] = "No Small";
$r["name"] = "Didn't get to name";
echo json_encode($r);
}
} else {
$r = "No image file";
echo json_encode($r);
}
if (!empty( $_POST["itemName"] )){
$r["name"] = $_POST["itemName"];
json_encode($r);
}
?>
Ok I am able to answer my own question, though I am not exactly sure about the theory that goes with it as I am relatively new to JS/Jquery. .serialize() does not work. I think this is because by definition, files are binaries and thus can not be serialized - but don't quote me. So you have to use FormData to send the file. I was aware of this but could not come up with the proper syntax for use with jquery validation 1.15. See the answer below. Hope it helps someone to save some time.
first correct the rookie mistake with my code: add type: 'post'
second: the variable to hold your form's data, including the input type="file" is this var formData = new FormData($('#useYourFormElementIdHere')[0]);
So the final is this:
$.ajax({
type: "POST",
url: "imgUploadTest.php",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
}).done({}).fail({}).always({})
I have a modal box that opens content from the footer of a page (a hidden div). I am trying to launch the modal and display the content of another .php file whilst passing a variable that can be used to SELECT from a DB Any ideas?
Here is the code:
The modal box link
Click Me For A Modal
The JS
(function($) {
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
The .php file with the modalbox content
<div id="myModal" class="reveal-modal">
<div>content called from DB using passed variable</div>
<p>more content</p>
<a class="close-reveal-modal">×</a>
Does anyone have any ideas please?
-----------------------------------------------------------------------------------
UPDATED!
Here is the full js file:
(function($) {
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'code.php',
data: '$varible',
type: 'GET',
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
var options = $.extend({}, defaults, options);
return this.each(function() {
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
Here is the html trigger:
<a class="big-link" href="#" data-reveal-id="myModal">Click Me to open modal</a>
Here is the code.php, file containing the modal:
<div id="myModal" class="reveal-modal"><div>content called from DB using passed variable</div><p>more content</p><a class="close-reveal-modal">×</a>
The issue at the minute is not passing the variable, but actually lauching the modal with the content of code.php
Thanks again for your time with this problem!
Without knowing what variables you're looking to pass, and what you're trying to grab, you can modify this. I haven't tested it so you may have to do some tweaking.
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'URL_TO_YOUR_PHP',
data: 'YOUR_VARIABLE', // Look at how to pass data using GET, or POST
type: 'GET' or 'POST', // Choose one, and pass the data above appropriately
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
-- EDIT --
Now the problem is that you don't have #myModal available in your HTML, yet. So, what you want to do is change the following line accordingly:
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
-- BECOMES --
$("body").append(output).reveal( $(this).data() );
In your CSS you'll want to initially hide your modal box that way it's revealed appropriately.
I am trying to send multiple files with one ajax call .
THe problem is i cant get my progress work out getting this line
TypeError: data.context is undefined
data.context.find('input').val(progress).change();
Cant figure out how to manage progress for each tpl with sendAPI >?I searched a lot try out different thing the basic reason for doing this is i want one ajax request and to have control after that request completes .
MYHTML
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div>
<div id="drop">
Drop Here <span style="color:white;text-transform:none;font-size: 13px"> OR <span>
<a>Browse</a>
<input type="file" name="upl[]" multiple/>
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</div>
</form>
MY JQUERY
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 100,
imageMaxHeight: 100,
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
dropZone: $('#drop'),
add: function(e, data) {
var type = data.files[0].type;
var size = data.files[0].size;
if ( type == 'image/jpeg' || type == 'image/png' || type == 'image/gif' ) {
if(size<=350000000)
{
// var preview = '<img src="' + URL.createObjectURL(data.files[0]) + '"/>';
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"' +
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><div class="preview"></div><p></p><span></span></li>');
tpl.find('p').text(data.files[0].name).append('<i>' + formatFileSize(data.files[0].size) + '</i>');
loadImage(data.files[0],
function(img) {
tpl.find('.preview').html(img);
},
{
minWidth: 80,
minHeight: 60, maxWidth: 80, maxHeight: 60, contain: true} // Options
);
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function() {
if (tpl.hasClass('working')) {
jqXHR.abort();
}
tpl.fadeOut(function() {
tpl.remove();
});
});
myfiles.push(data.files[0]);
} else{
noty({type:'error',text: 'file exceeds limit of 350Kb'});
}//check for file type
} else
{
noty({type:'error',text: 'Invalid file type.Please make sure image has valid extension jpeg|gif|jpg'});
}
// $('#post_picture').on('click',function(){
//
//
//
// var jqXHR = data.submit().success(function (result, textStatus, jqXHR) {ar.push(result)});
//
//
// tpl.fadeOut(function() {
// tpl.remove();
// });
// $('#post_picture').off('click');
//
//
//
// });
},
complete:function(e,data)
{
},
progress: function(e, data) {
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if (progress == 100) {
data.context.removeClass('working');
}
},
fail: function(e, data) {
// Something has gone wrong!
data.context.addClass('error');
}
});
$(document).on('click','#post_picture',function(){
alert('asdas');
$('#upload').fileupload('send', {files: myfiles});
});
This is how i did it Why do these days no body answers :)
var myfiles = [];
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 100,
imageMaxHeight: 100,
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
dropZone: $('#drop'),
add: function(e, data) {
var type = data.files[0].type;
var size = data.files[0].size;
if (type == 'image/jpeg' || type == 'image/png' || type == 'image/gif') {
if (size <= 350000000)
{
// var preview = '<img src="' + URL.createObjectURL(data.files[0]) + '"/>';
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"' +
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><div class="preview"></div><p></p><span></span></li>');
tpl.find('p').text(data.files[0].name).append('<i>' + formatFileSize(data.files[0].size) + '</i>');
loadImage(data.files[0],
function(img) {
tpl.find('.preview').html(img);
},
{
minWidth: 80,
minHeight: 60, maxWidth: 80, maxHeight: 60, contain: true} // Options
);
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function() {
if (tpl.hasClass('working'))
{
data='';
}
tpl.fadeOut(function() {
tpl.remove();
});
});
// myfiles.push(data.files[0]);
} else {
noty({type: 'error', text: 'file exceeds limit of 350Kb'});
}//check for file type
} else
{
noty({type: 'error', text: 'Invalid file type.Please make sure image has valid extension jpeg|gif|jpg'});
}
$('#post_picture').on('click', function() {
if(data!='')
{
var jqXHR = data.submit().success(function(result, textStatus, jqXHR) {
});
}
tpl.fadeOut(function() {
tpl.remove();
});
$('#post_picture').off('click');
});
},
stop: function(e) {
console.log(myfiles);
},
progress: function(e, data) {
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if (progress == 100) {
data.context.removeClass('working');
}
},
fail: function(e, data) {
// Something has gone wrong!
data.context.addClass('error');
}
}).on('fileuploaddone', function(e, data) {
myfiles.push(data.result);
});
I click 'Add files' choose a file it then creates a thumbnail (depending on browser) and displays the 'Upload' button beneath it.
when I click 'Upload', sometimes it uploads the file and says 'File upload failed.' - the file is actually uploaded but I still get this message. Sometimes it doesn't upload and i get the same message.
I have two errors -
1st is in the PHP error log 'PHP Warning: exif_imagetype(): Filename cannot be empty in ***\***\UploadHandler.php' I don't get it all the time though.
2nd is jquery.validation on the page - 'Uncaught Error: Syntax error, unrecognized expression: [name=files[]]'
In the debugger it jumps straight to '.on('fileuploadfail', function (e, data)' without going anywhere else and once that completes it refreshes the whole page..guess I need a 'return false' somewhere?
Thanks for your help.
HTML:
<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>
Javascript:
var filepower = function () {
'use strict';
var url = 'server/php/',
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, file) {
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');
};
You didn't post your source code, but if you can add to the response on the server, then you can fix it by implementing the return structure here:
https://github.com/blueimp/jQuery-File-Upload/wiki/JSON-Response
I can't help you if you can't change the server, though the library author says there's a way to modify/over-ride the expected JSON fields so it doesn't error out.
Either return an appropriate expected response from the server or get data.jqXHR . this will contain the response from the server. you can use that to check whether upload was successful or not.
I've been working for a bit on this code, making in function just as I'd like it, but in the end I guess I missed something pretty big: the files don't seem to be uploading. The progress bar has been perfectly tweaked, the dialog box works well, just no files are being uploaded.
What's going on?
My Javascript:
fileCount = 0;
barWidth = 0;
$(function() {
var uploader = new plupload.Uploader({
runtimes : 'flash',
browse_button : 'pickfiles',
max_file_size : '10mb',
url : 'js/upload/upload.php',
resize : {width : 700, height : 700, quality : 90},
flash_swf_url : 'js/upload/plupload.flash.swf',
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
]
});
uploader.bind('Init', function(up, params) {
});
uploader.bind('FilesAdded', function(up, files) {
$.each(files, function(i, file) {
fileCount ++
$('#uploadfiles').fadeIn(200);
$('#filelist').append(
'<div id="' + file.id + '">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
'</div>');
});
});
uploader.bind('FileUploaded', function(up, file) {
console.log(file.name);
$('#'+ file.id).fadeOut(200);
});
uploader.bind('UploadProgress', function(up, file) {
barWidth = barWidth+(file.percent/fileCount)
$('#progressBar').animate({"width":barWidth+"%"},300);
if (barWidth == 100 ) {$('#progressBox').delay(2000).fadeOut(200)};
});
$('#uploadfiles').click(function(e) {
e.preventDefault();
$('#filelist').fadeIn(200, function() {
$('#progressBox').fadeIn(200, function() {
uploader.start();
});
});
});
uploader.init();
});
My HTML (updated per comment below):
<form method="post" action="js/upload/upload.php" enctype="multipart/form-data">
<div>
<button id="pickfiles" href="#">Add...</button>
<button id="uploadfiles" href="#">Upload</button>
<br />
<div id="filelist"></div>
<div id="progressBox"><div id="progressBar"></div></div>
</div>
</form>
I think your answer lies in what the upload.php file does when it receives the post. Check the file associated wiuth your config line:
url : 'js/upload/upload.php'
I had a similar problem (in ASP.NET) where the upload directory did not exist.
Hope that helps.