I want the image uploaded to my server with Ajax. But I must compress it before uploading because the image sizes will be huge. I found a script called browser-image-compression. I've been trying this script in AJAX for about 5 hours, but I couldn't. Ajax still sending a original size. I'm pretty new to Javascript.
Script https://github.com/Donaldcwl/browser-image-compression
JSfiddle https://jsfiddle.net/rd8f6vqu/2/
I opening the image loading screen with sweetalert2.
myfunction
function addImage (image_type, game) {
var confirmText = 'Submit';
var cancelText = 'Cancel';
var main_title = 'Title';
var img_icon = '<span class="material-symbols-outlined gp-imageupload-titleicon">swords</span>';
Swal.fire({
customClass: {
container: 'gp-imageupload-body',
popup: 'swall-custom-backgroundcolor swall-custom-border',
title: 'swall-custom-title',
htmlContainer: 'swall-custom-textcolor',
icon: 'swall-custom-icon',
validationMessage: 'swall-custom-validatormsg',
},
title: main_title,
iconHtml: img_icon,
html:
'<div class="gp-imageupload-box">' +
'<form action="#" id="gp-imageupload-sendForm">' +
'<div id="gp-imageupload-drop-area">' +
'<label for="gp-imageupload-fileElem">' +
'<input type="file" name="uploaded_image" id="gp-imageupload-fileElem" onchange="handleFiles(this.files)" />' +
'<div class="uploadIcon">' +
'<i class="fa fa-cloud-upload fa-4x" aria-hidden="true"></i>' +
'<p>Paste Image <span class="or">or</span> Drag & Drop <span class="or">or</span> Click & Select</p>' +
'<p class="last">Only jpeg, jpg and png</p>' +
'</div>' +
'<div id="gp-imageupload-gallery"></div>' +
'</label>' +
'<div class="gp-imageupload-control-panel">' +
'<div class="item">' +
'<div id="delete-image"><span class="material-symbols-outlined">delete_forever</span></div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="progress-wrapper">' +
'<div class="progress-info">' +
'<div class="progress-percentage">' +
'<span class="text-sm font-weight-bold" id="gp-imageupload-progressbar-span">0%</span>' +
'</div>' +
'</div>' +
'<div class="progress">' +
'<div class="progress-bar bg-primary" id="gp-imageupload-progressbar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
'</div>' +
'</div>' +
'<div id="gp-imageupload-details_img">' +
'<div class="list">' +
'<div class="item">' +
'<div class="attr">Name</div>' +
'<div class="data" id="nameImage">No Data</div>' +
'</div>' +
'<div class="item">' +
'<div class="attr">Size</div>' +
'<div class="data" id="sizeImage">No Data</div>' +
'</div>' +
'<div class="item">' +
'<div class="attr">Type</div>' +
'<div class="data" id="typeImage">No Data</div>' +
'</div>' +
'</div>' +
'</div>' +
'</form>' +
'</div>' +
'<div id="gp-imageupload-container-image"></div>',
showCloseButton: false,
showCancelButton: true,
focusConfirm: false,
confirmButtonText: confirmText,
cancelButtonText: cancelText,
showLoaderOnConfirm: true,
preConfirm: function() {
var ext = $('#gp-imageupload-fileElem').val().split('.').pop().toLowerCase();
console.log(ext);
if($.inArray(ext, ["jpg","jpeg","png"]) == -1) {
Swal.showValidationMessage(
`Error`
)
}
},
}).then((result) => {
if(result.value){
var file_input = $('#gp-imageupload-fileElem');
var progress_bar = $('#gp-imageupload-progressbar');
var progress_percent = $('#gp-imageupload-progressbar-span');
var original_file = $('#gp-imageupload-fileElem')[0].files[0];
const options = {
maxWidthOrHeight: 1000,
useWebWorker: true
}
imageCompression(original_file, options)
.then(function (compressedFile) {+
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});
var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
$.ajax({
url: 'editimage.php',
type: 'POST',
data: filedata,
dataType: "json",
cache:false,
contentType: false,
processData: false,
beforeSend: function() {
var percentVal = '0%';
var percentVal2 = '0';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
progress_bar.attr("aria-valuenow", percentComplete);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
complete: function(xhr) {
var percentVal = '100%';
var percentVal2 = '100';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
success: function(result){
if (result.status == true) {
}
else {
}
}
});
}else {
window.removeEventListener('paste', pasteImage);
}
});
window.nodata_text = 'No Data';
$.getScript( "/assets/js/imageuploader.js?ver=111" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
};
console.log
xxxx Uncaught (in promise) ReferenceError: compressedFile is not defined
at xxxx
compressedFile instanceof Blob true
xxxx compressedFile size 0.12560653686523438 MB
imageuploader.js
// ************************ Drag and drop ***************** //
//# sourceURL=/assets/js/imageuploader.js?ver=111
var dropArea = document.getElementById("gp-imageupload-drop-area")
var fileElem = document.getElementById('gp-imageupload-fileElem');
var gallery = document.getElementById('gp-imageupload-gallery');
// Prevent default drag behaviors
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
dropArea.addEventListener('DOMNodeInserted',function () {
$('.uploadIcon').css('display','none');
if($('#gp-imageupload-gallery').children().length > 1) {
$('#gp-imageupload-gallery').children().first().remove();
}
});
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
function handleDrop(e) {
e.preventDefault();
var fileInput = document.getElementById("gp-imageupload-fileElem");
fileInput.files = e.dataTransfer.files;
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
function handleFiles(files) {
files = [...files];
files.forEach(previewFile);
}
function previewFile(file) {
var reader = new FileReader();
reader.onloadend = function() {
dropArea.style.height = '100%';
let img = document.createElement('img');
img.src = reader.result
gallery.appendChild(img);
setDataForImage(file);
}
reader.readAsDataURL(file);
}
//********************paste********************//
//var input = document.querySelector("#gp-imageupload-text");
var pasteImage = function(event){
const fileInput = document.getElementById("gp-imageupload-fileElem");
fileInput.files = event.clipboardData.files;
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function(event){
let img = document.createElement('img')
img.src = event.target.result
document.getElementById('gp-imageupload-gallery').appendChild(img);
setDataForImage(blob);
};
reader.readAsDataURL(blob);
}
}
}
window.addEventListener("paste", pasteImage);
function setDataForImage(file)
{
var nameImage = $('#nameImage');
var sizeImage = $('#sizeImage');
var typeImage = $('#typeImage');
//var timemodifiImage = $('#timemodifiImage');
//var datemodifiImage = $('#datemodifiImage');
var filesizetoMB = file.size / 1024 / 1024;
console.log('file',file);
nameImage.text(file.name);
sizeImage.text(filesizetoMB.toFixed(2)+' MB');
typeImage.text(file.type);
//timemodifiImage.text(file.lastModified);
//datemodifiImage.text(file.lastModifiedDate);
}
var deleteImageBtn = $('#delete-image');
deleteImageBtn.click(function(){
var image = $('#gp-imageupload-gallery').children().first().remove();
var nameImage = $('#nameImage');
var sizeImage = $('#sizeImage');
var typeImage = $('#typeImage');
$('.uploadIcon').css('display','flex');
fileElem.value = "";
nameImage.text(nodata_text);
sizeImage.text(nodata_text);
typeImage.text(nodata_text);
});
Okay, I figured it out.
xxxx Uncaught (in promise) ReferenceError: compressedFile is not defined
This happens because of Promise()
A Promise in Javascript represents an action that has already started,
but one that will be completed at a later time.
When I look with the Chrome breakpoint, the following code
filedata.append('file', compressedFile);
is sent before the
imageCompression(original_file, options)
.then(function (compressedFile) {+
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});
That's why it returns undefined. To solve this I include the $.ajax code in a function. Like this,
function ajaxpost (dataForm) {
$.ajax({
// some ajax codes
});
}
Then I call this function inside promise and everything is resolved.
imageCompression(original_file, options)
.then(function (compressedFile) {
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeM
var file_Type = compressedFile.type.split('/').pop().toLowerCase();
var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
filedata.append('file_type', file_Type);
ajaxpost(filedata);
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});
Final code here;
imageCompression(original_file, options)
.then(function (compressedFile) {
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeM
var file_Type = compressedFile.type.split('/').pop().toLowerCase(); // compressedFile.type = image/png. With this code I only get the last "png".
var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
filedata.append('file_type', file_Type);
ajaxpost(filedata);
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});
function ajaxpost (dataForm) {
$.ajax({
url: 'editgameprofile.php',
type: 'POST',
data: dataForm,
dataType: "json",
cache:false,
contentType: false,
processData: false,
beforeSend: function() {
var percentVal = '0%';
var percentVal2 = '0';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
progress_bar.attr("aria-valuenow", percentComplete);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
complete: function(xhr) {
var percentVal = '100%';
var percentVal2 = '100';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
success: function(result){
if (result.status == true) {
}
else {
}
}
});
}
Related
I have method to upload images to Flask in JavaScript. Below is the code used to upload images and display text in chatbot. This is used in my Chatbox class on button click:
For text there is no issue, it's working fine. However when uploading an image, previously uploaded images are getting deleted, ie. the previous img tag src is not visible in the DOM inspector.
var i = 1;
let formData = new FormData();
formData.append('question', $("#question").val());
formData.append('questionImageFile', $("#question-image")[0].files[0]);
let question_id = $("#question").val();
let question_image_file = $("#question-image")[0].files[0];
let msg1;
if ($("#question").val() === "" && $("#question-image")[0].files[0] === "")
return;
else if ($("#question").val() != "")
msg1 = {
name: "User",
message: question_id,
timestamp: new Date().toLocaleTimeString()
}
else {
var imgMsg = '<img id="' + i + '"/>'
msg1 = {
name: "User",
message: imgMsg,
timestamp: new Date().toLocaleTimeString()
}
}
this.messages.push(msg1);
$.ajax({
type: "POST",
url: "/chatbot",
data: formData,
cache: false,
processData: false,
contentType: false,
success: (result) => {
let msg2 = {
name: "Sam",
message: result.response,
timestamp: new Date().toLocaleTimeString()
};
this.messages.push(msg2);
var html = '';
this.messages.slice().reverse().forEach(function(item, index) {
if (item.name === "Sam") {
$("#question").val() + '</div>' + '<div class="chatbotResponse"><div class="timeBot">' + new Date().toLocaleTimeString() + '</div>' + result.response + '</div>'
html += '<div class="messages__item messages__item--visitor">' + '<div class="timeBot">' + item.timestamp + '</div>' + item.message
if (item.message.startsWith("Sorry, I")) {
html += '<button type="button" class="btn btn-outline-primary" id="feedbackBtn" data-toggle="modal" data-target="#exampleModal">Go to feedback form</button>'
}
html += '</div>'
} else {
html += '<div class="messages__item messages__item--operator">' + '<div class="timeUser">' + item.timestamp + '</div>' + item.message + '</div>'
}
});
const chatmessage = chatbox.querySelector('.chatbox__messages');
chatmessage.innerHTML = html;
if (formData.get('questionImageFile')) {
console.log(i)
var output = document.getElementById(i);
output.src = window ? .URL ? .createObjectURL(formData.get('questionImageFile'));
i = i + 1;
}
// $("#question").val()
$("#question").val("");
},
error: function(result) {
alert('error');
this.updateChatText(chatbox)
$("#question").val("");
}
});
this is my problem.
I have an input to upload several files at the same time, then I have an ajax that is responsible for sending the request and events listener to load the bars.
The problem is when I upload 8 files and some do not meet the validations (size and format), then draw most of the bars and the last ones do not.
The file is uploaded but neither the bar nor the text is drawn
This is the javascript code
<script type="text/javascript">
var newFileList = [];
$('.addfiles').on('click', function () { $('#fileUploader').click(); return false; });
$(document).ready(function () {
$('input[type=file]').change(function () {
if (this.files.length != 0) { $("#btnUpload").attr('disabled', false); };
$("#bars").remove();
$("#divFiles").append('<div id="bars"></div>')
for (var i = 0; i < this.files.length; i++) { //Progress bar and status label's for each file genarate dynamically
var fileId = i;
const file = this.files[i];
if (validateFileExtension(file)) {
$("#bars").append(
'<div id = "' + fileId + '" >' +
'<div>' + file.name + '</div>' +
'<div class="progress">' +
'<div class="bar" id="progressbar_' + fileId + '" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>' +
' </div>' +
'<div>' +
'<input type="button" class="btn btn-danger" style="display:none;line-height:6px;height:25px" id="cancel_' + fileId + '" value="cancel">' +
'</div>' +
'<div>' +
'<p class="progress-status" style="text-align: right;margin-right:-15px;font-weight:bold;color:saddlebrown" id="status_' + fileId + '"></p>' +
'</div>' +
'<div>' +
'<p id="notify_' + fileId + '" style="text-align: right;"></p>' +
'</div>' +
'</div>'
);
}
};
$('file_count').text('# Files selected: ' + newFileList.length);
})
});
function uploadFiles() {
var file = document.getElementById("fileUploader")//All files
for (var i = 0; i < newFileList.length; i++) {
uploadSingleFile(newFileList[i], i);
}
}
function uploadSingleFile(file, i) {
var fileId = i;
var ajax = new XMLHttpRequest();
//Progress Listener
ajax.upload.addEventListener("progress", function (e) {
console.log(file);
var percent = (e.loaded / e.total) * 100;
$("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
$('#progressbar_' + fileId).css("width", percent + "%")
$("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
}, false);
//Load Listener
ajax.addEventListener("load", function (e) {
$("#status_" + fileId).text("File upload!");
$('#progressbar_' + fileId).css("width", "100%")
//Hide cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.hide();
}, false);
//Error Listener
ajax.addEventListener("error", function (e) {
$("#status_" + fileId).text("Upload Failed");
}, false);
//Abort Listener
ajax.addEventListener("abort", function (e) {
$("#status_" + fileId).text("Upload Aborted");
}, false);
var imagePath = window.location.search;
var filePath = imagePath.replace("imagePath", "filePath");
ajax.open("POST", "/File"+filePath); // Your API .net, php
var uploaderForm = new FormData(); // Create new FormData
uploaderForm.append("file", file); // append the next file for upload
ajax.send(uploaderForm);
//Cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.show();
_cancel.on('click', function () {
ajax.abort();
})
}
function validateFileExtension(file) {
if (!/(\.bmp|\.jpg|\.gif|\.png)$/i.test(file.name)) {
bootbox.alert("Invalid file type:" + file.name + " . Only JPG, GIF, PNG or BMP File");
return false;
}
// Validate Size
var imgsize = document.getElementById('ImgSize').value;
var size = file.size;
// check file size
if (size > imgsize) {
$(this).val("");
bootbox.alert("The size of " + file.name + " is too big: " + size + " Byte, you only can upload " + imgsize + " Byte");
return false;
}
newFileList.push(file);
return true;
}
</script>
EDIT
apply the changes but follow the same problem the file is uploaded, but the bar is not drawn on the screen or anything else
function uploadFiles() {
filesToUpload = newFileList.slice(0);
uploadSingleFile(filesToUpload.pop(), 0); // start the process here
}
function uploadSingleFile(file, i) {
var fileId = i;
var ajax = new XMLHttpRequest();
//Progress Listener
ajax.upload.addEventListener("progress", function (e) {
var percent = (e.loaded / e.total) * 100;
$("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
$('#progressbar_' + fileId).css("width", percent + "%")
$("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
}, false);
//Load Listener
ajax.addEventListener("load", function (e) {
$("#status_" + fileId).text("File upload!");
$('#progressbar_' + fileId).css("width", "100%")
//Hide cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.hide();
}, false);
//Error Listener
ajax.addEventListener("error", function (e) {
$("#status_" + fileId).text("Upload Failed");
}, false);
//Abort Listener
ajax.addEventListener("abort", function (e) {
$("#status_" + fileId).text("Upload Aborted");
}, false);
var imagePath = window.location.search;
var filePath = imagePath.replace("imagePath", "filePath");
ajax.open("POST", "/File" + filePath); // Your API .net, php
var uploaderForm = new FormData(); // Create new FormData
uploaderForm.append("file", file); // append the next file for upload
ajax.send(uploaderForm);
ajax.onreadystatechange = function () {
if (ajax.readyState === 4) {
if (ajax.status === 200) {
console.log('successful');
if (filesToUpload.length > 0) { // do this inside your ajax success call
uploadSingleFile(filesToUpload.pop(), ++i);
}
else {
console.log(ajax.status);
console.log('failed');
}
}
}
}
//Cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.show();
_cancel.on('click', function () {
ajax.abort();
})
}
I'm using blueimp/jQuery-File-Upload's plugin to upload files and I'm trying (unsuccessfully) to add a data-attribute to the preview when the upload is done.
Here is the code:
$('#fileupload').fileupload({
autoUpload: true,
disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|doc?x|pdf|xml|psd|tif)$/i,
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-upload fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
'<div class="error"></div>' +
'<div class="progress"></div>' +
(!index && !o.options.autoUpload ?
'<button class="start" disabled>Start</button>' : '') +
(!index ? '<button class="cancel">Cancel</button>' : '') +
'</td>' +
'</div>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-download fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
(file.error ? '<div class="error"></div>' : '') +
//'<button class="delete">Delete</button>' +
'</div>');
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.name').text(file.name);
row.find('.error').text(file.error);
} else {
row.find('.name').append($('<a></a>').text(file.name));
if (file.thumbnailUrl) {
row.find('.preview').append(
$('<a></a>').append(
$('<img>').prop('src', file.thumbnailUrl)
)
);
}
row.find('a')
.attr('data-gallery', '')
.prop('href', file.url);
row.find('button.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
}
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
}).bind('fileuploaddone', function(e, data) {
var arquivo = data.result.files[0].url;
var varCodTipoProcesso = $('.indexador-campo').data('cod-tipo-processo');
var varCodEstabelecimento = $('.estabelecimento-select').parent().children('a').children('span').data('cod-estabelecimento');
var varArrayCampos = [];
var tipos = ['jpg', 'png', 'gif', 'psd', 'bmp', 'tif', 'pdf', 'xml'];
var nome = data.result.files[0].name;
var today = new Date();
var s = today.getSeconds();
var i = today.getMinutes();
var h = today.getHours();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
now = '' + yyyy + mm + dd + h + i + s;
var filename = now + '.' + nome.substr(nome.lastIndexOf('.')+1);
$('.indexadores-campos .row input').each(function() {
var indexadoresData = {};
indexadoresData.nomCampo = $(this).attr('name');
indexadoresData.numOrdem = $(this).data('num-ordem');
indexadoresData.valor = $(this).val();
varArrayCampos.push(indexadoresData);
});
console.log(varCodTipoProcesso)
$.getJSON('/sistema/ajax/setUploadFileJson.php', {
arquivo: arquivo,
varCodProcesso: null,
varCodTipoProcesso: varCodTipoProcesso,
varCodEstabelecimento: varCodEstabelecimento,
varCodTipoDocumento: null,
varArrayCampos: varArrayCampos,
pasta: null,
tipos: tipos,
nome: filename
}).done(function(doc) {
console.log(data.codDocumento); //there's the data I want to add to the preview
}).fail(function() {
console.log('error');
});
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>').text('Upload server currently unavailable - ' + new Date()).appendTo('#fileupload');
});
}
// Load & display existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
I managed to get the data from the server, but douldn't add it to the preview and I can't figure out how to do it. Can anybody help me on this?
The answered is already available and both will work fine.
You need to use additional plugin jquery.fileupload-ui.js as mentioned in answer (https://stackoverflow.com/a/11016888/2871356) or as mentioned in answer(https://stackoverflow.com/a/18284685/2871356) Place this inside your add(e, data) callback function, adjusting for your own html elements accordingly:
$('body').append('<img src="' + URL.createObjectURL(data.files[0]) + '"/>');
Please see the code below:
$.ajax({
type: "POST",
url: "Results1.aspx/TableQuery",
data: JSON.stringify({
mappingid: res[i],
strCon: $("#fieldGenieConnectionString")[0].value,
strTypeSession: $("#fieldTypeSession")[0].value
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i, res.length),
error: OnError,
failure: function (response) {
alert('there was a failure loading the webpage')
}
});
and the code below:
function OnSuccess(i, totalrows) {
return function (response) {
//if (response.d != "") {
var strResponse = response.d;
strResponse = strResponse.toUpperCase;
if (strResponse.indexOf("<TR>") > 0) {
// alert(response.d);
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
numSucceeded++;
var completeCalculation = (numSucceeded / totalrows) * 100
var rounded = completeCalculation.toFixed(0);
document.getElementById('ProgressIndicator').innerHTML = rounded + ' % complete';
document.getElementById('ProgressIndicator2').innerHTML = rounded + ' % complete';
if (numSucceeded === totalrows) {
var end = new Date().getTime();
var htmlResponse = "Loaded after: " + (end - start) / 1000 + " seconds"
document.getElementById('TotalTimeLabel').innerHTML = htmlResponse;
document.getElementById('TotalTime2Label').innerHTML = htmlResponse;
$("#LoadingImage").hide();
$("#LoadingImage2").hide();
}
}
}
The following line causes an error:
if (strResponse.indexOf("<TR>") > 0) {
strResponse = strResponse.toUpperCase;
There is a typo here. I think you want to write strResponse = strResponse.toUpperCase();
You are assigning a function to strResponse instead of calling the toUpperCase() on the existing strResponse
I am using formdata and XMLHttpRequest to submit my form using ajax. Now everything works well on other browsers except IE 11 . Note I am uploading a file using this ajax request.
My code is as follows
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.responseType = "json";
xhr.send(formData);
xhr.onload = function (e) {
var new_message_response = xhr.response; // not responseText
console.log(new_message_response);
if (new_message_response.conversationStatus) {
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled',true);
} else {
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null) {
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
}
I have used jQuery.ajax instead of XMLhttpRequest now everything works smooth as silk :) Now my code looks like this:
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
jQuery.ajax({
url: form.getAttribute('action'),
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
var new_message_response = data;
if (new_message_response.conversationStatus)
{
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled', true);
}
else
{
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null)
{
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
},
error: function (data) {
alert("error");
}
});