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 {
}
}
});
}
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("");
}
});
I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.
I am working on a MVC4 C#.Net project and when I am trying to
click the button ('#btn_rightArw_Dwn') then the ajax call fires multiple times in MVC4. Why this is happening? Please look up on below jQuery code.
Below I have added jQuery code.
$("#btn_rightArw_Dwn").click(function() {
$('.fade_bg').show();
var Masterid = $('#MastersId').val();
var pgm_id = $('#program1').val();
if ($('#rdclick').val() == "0") {
$.ajax({
url: "/DataInput/Arrow_Load_Down?Id=" + Masterid + "&flag=" + "Right" + "&type=" + 0 + "&pgm_id=" + pgm_id,
async: true,
data: {},
success: function(data) {
$('#DVmaster').html(data);
$('#btn_rightArw1').attr('hidden', false);
$('#btn_LeftArw1').attr('hidden', false);
var production_id = $('#program1').val();
$.ajax({
url: "/DataInput/Arrow_Load_Details_Down?Id=" + Masterid + "&flag=" + "Right" + "&ProductnSts_id=" + pgm_id + "&type=" + 0,
async: false,
data: {},
success: function(data) {
$('#DVDetails').html(data);
$('#DVDetails').show();
$('#btn_rightArw_Dwn').attr('hidden', false);
$('#btn_LeftArw_dwn').attr('hidden', false);
},
error: function(html) {
$('.fade_bg').hide();
}
});
var channelid = $("#channel1").val();
var starttime = $("#StartTime").val();
var Endtime = $("#EndTime").val();
var date = $("#Date").val();
var Vimpact = $("#Viewers").val();
var gradeid = $("#grade1").val();
var seclength = $("#Seconds option:selected").text();
var Daypartid = $('#daypartid').val();
var itemid = $('#item1 option:selected').val();
var brandid = $("#brand1 option:selected").val();
$.ajax({
url: "/DataInput/Print_Labels_in_Edit?starttime=" + starttime + "&finishtime=" + Endtime + "&date=" + date + "&channelid=" + channelid + "&impact1=" + Vimpact + "&Seclength=" + seclength + "&gradesid=" + gradeid + "&itemid=" + itemid + "&brandid=" + brandid,
cache: false,
success: function(html) {
var labels = html.split(',');
var daypartname = labels[0];
var CPH = labels[1];
var TVR = labels[2];
var Mediavalue = labels[3];
var daypartid = labels[4];
$('.fade_bg').hide();
$('#lblDaypart').text(" " + daypartname);
$("#lblCPH").text('£' + " " + CPH);
$('#lblTvr').text(" " + TVR);
$('#lblMediaValue').text(" " + "£ " + Mediavalue);
$('#daypartid').val(daypartid);
},
error: function(html) {
$('.fade_bg').hide();
}
});
}
});
}
});
Thanks in advance.
I have an RSS reader that fetches events with ajax. I want the user to be able to click the link of the event and have it transition to a new page with the details. Here is an example I found: http://jsfiddle.net/hellosze/t22QP/ I am have trouble understanding what is happening since I am rather new to jQuery so I was hoping someone code direct me as to what is happening. Thanks!
Here is how I extract the xml data and display it to a main page:
$.ajax({
type: 'GET',
url: 'categoryURL',
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item:lt(40)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var dateDisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (dateDisplay.length > 35) { dateDisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
var item = {title: displayTitle, DateDecription: dateDisplay, Date: new Date(eventDate), Region: region,}
data.push(item);
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
}); //END .each()
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a>b ? -1 : a<b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + "Event Date: " + item.DateDecription + '</p><p>' + "Location: " + item.Region + '</p');
});
} //END success fn
});
});