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");
}
});
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 have a rather large and complex code of SVG that generates using JavaScript and jQuery dynamically based on the pages information.
I then have an AJAX post save.
What am I failing to do to convert this to post the image data properly?
var canvas = $("#canvas")[0];
var string= canvas.toDataURL("image/png");
base64=string.replace("data:image/png;base64,", "");
var rid = kRid || "";
var fileN = " Product " + rid + ".png";
var req = "";
req += "<qdbapi>";
req += "<field fid='323' filename='" + fileN + "'>" + base64 + "</field>";
req += "</qdbapi>";
$.ajax({
type: "POST",
contentType: "text/xml",
dataType: "xml",
processData: false,
//url altered
url: "https://removed.quickbase.com/db/removedDBID?act=API_EditRecord&rid=" + rid,
data: req,
success: function(responce) {
//auto reload page
var str = window.location.href;
setTimeout(function() {
window.location.href = str;
}, 5000);
}
})
The idea came from this snippet of code that I used else ware to get current PNG files and move them:
$.get(url, function(xml) {
var promises = [];
$("record", xml).each(function() {
var url = $("f#9 url", this).text();
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var arrayBuffer = xhr.response;
var base64 = btoa([].reduce.call(new Uint8Array(arrayBuffer), function(p, c) {
return p + String.fromCharCode(c)
}, ''))
var req = "";
req += "<qdbapi>";
req += "<field fid='6' filename='" + name + "'>" + base64 + "</field>";
req += "<field fid='54' >" + Rid + "</field>";
req += "<field fid='44' >" + comment + "</field>";
req += "</qdbapi>";
... then the AJAX post.
I do not have access to do this via PHP.
(Posted on behalf of the OP).
I forgot to add == to mark the end of the file so:
var string= canvas.toDataURL("image/png");
string+="==";
base64=string.replace("data:image/png;base64,", "");
and huzza it works...
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]) + '"/>');
I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.