Answer the question
In order to leave comments, you need to log in
How to submit using jquery ajax a file along with form data?
And hello again friends! And again zaparka with jquery. There is a form to add some data and a file. I took the plugin for adding a file from this friend, the demo is there:
https://github.com/danielm/uploader
That's all you need and that's enough. I know that there is cooler, but I'll deal with it as soon as there is too much time:
https://blueimp.github.io/jQuery-File-Upload/
In general, I took the first option, I liked the debug console very much besides.
I remade a little demo for myself, translated everything into Russian. And the task is the following:
The data from the form will be added to the database along with a link to the image. The name of the image file will be made up of this form data. But I just can’t send it all in one request, if it’s possible, then I don’t have enough knowledge of jquery and ajax.
I started building a bike.
$(".cloth_add").submit(function() {
$.ajax({
type: "POST",
url: "upload.php",
data: $(".cloth_add").serialize(),
cache: true,
success:
function processData(data) {
fileUpload('#cloth-upload', 'upload.php', 1, data);
alert(data);
}
});
return false;
});
function fileUpload (block, handler, numberOfFiles, filename) {
$(document).ready(function() {
$(block).dmUploader({
url: handler,
maxFiles: numberOfFiles,
fileName: filename,
dataType: 'html',
allowedTypes: 'image/*',
onInit: function(){
$.fileUpload.addLog('#upload-debug', 'default', 'Готов к загрузке');
},
onBeforeUpload: function(id){
$.fileUpload.addLog('#upload-debug', 'default', 'Началась загрузка файла #' + id);
$.fileUpload.updateFileStatus(id, 'default', 'Загрузка...');
},
onNewFile: function(id, file){
$.fileUpload.addFile('#upload-files', id, file);
/*** Begins Image preview loader ***/
if (typeof FileReader !== "undefined"){
var reader = new FileReader();
// Last image added
var img = $('#upload-files').find('.upload-image-preview').eq(0);
reader.onload = function (e) {
img.attr('src', e.target.result);
}
reader.readAsDataURL(file);
} else {
// Hide/Remove all Images if FileReader isn't supported
$('#upload-files').find('.upload-image-preview').remove();
}
/*** Ends Image preview loader ***/
},
onComplete: function(){
$.fileUpload.addLog('#upload-debug', 'default', 'Все загрузки завершены');
},
onUploadProgress: function(id, percent){
var percentStr = percent + '%';
$.fileUpload.updateFileProgress(id, percentStr);
},
onUploadSuccess: function(id, data){
$.fileUpload.addLog('#upload-debug', 'success', 'Загрузка файла #' + id + ' завершена');
$.fileUpload.addLog('#upload-debug', 'info', 'Получен ответ от сервера для файла #' + id + ': ' + JSON.stringify(data));
$.fileUpload.updateFileStatus(id, 'success', 'Загрузка завершена');
$.fileUpload.updateFileProgress(id, '100%');
},
onUploadError: function(id, message){
$.fileUpload.updateFileStatus(id, 'error', message);
$.fileUpload.addLog('#upload-debug', 'error', 'Не удалось загрузить файл #' + id + ': ' + message);
},
onFileTypeError: function(file){
$.fileUpload.addLog('#upload-debug', 'error', 'File \'' + file.name + '\' Файл не является изображением и не может быть добавлен');
},
onFileSizeError: function(file){
$.fileUpload.addLog('#upload-debug', 'error', 'File \'' + file.name + '\' Файл не может быть добавлен так как превышен допустимый размер');
},
onFallbackMode: function(message){
$.fileUpload.addLog('#upload-debug', 'info', 'Браузер не поддерживается(попробуйте сделать следующее!): ' + message);
}
});
});
}
// Ajax Submit
$.ajax({
url: widget.settings.url,
type: widget.settings.method,
dataType: widget.settings.dataType,
data: fd,
cache: false,
contentType: false,
processData: false,
forceSync: false,
xhr: function(){
var xhrobj = $.ajaxSettings.xhr();
if(xhrobj.upload){
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total || e.totalSize;
if(event.lengthComputable){
percent = Math.ceil(position / total * 100);
}
widget.settings.onUploadProgress.call(widget.element, widget.queuePos, percent);
}, false);
}
return xhrobj;
},
success: function (data, message, xhr){
widget.settings.onUploadSuccess.call(widget.element, widget.queuePos, data);
},
error: function (xhr, status, errMsg){
widget.settings.onUploadError.call(widget.element, widget.queuePos, errMsg);
},
complete: function(xhr, textStatus){
widget.processQueue();
}
});
};
$.fn.dmUploader = function(options){
return this.each(function(){
if(!$.data(this, pluginName)){
$.data(this, pluginName, new DmUploader(this, options));
}
});
};
Answer the question
In order to leave comments, you need to log in
I figured out something, there is such an option there:
extraData: {
varName:1,
varName:'string'
}
// Append extra Form Data
$.each(widget.settings.extraData, function(exKey, exVal){
fd.append(exKey, exVal);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question