I have a image upload form with an input type file and attribute multiple.
When i select all the images for upload it calls 'index.php?controller=produse_add&method=uploadmultiple' and uploads the images in one ajax call.
How can i upload all the selected files in one ajax call for every 2 files?
For example if i have 8 images selected to have 4 ajax calls.
$s("#multiple-photos").on('change', handleFileSelect);
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var formData = new FormData();
var parallelFiles = 2;
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = '<li class="dz-image-preview"><div class="documents_drop_file_thumb"><div class="picture_menu menu-overlay"><div class="picture_thumb_image"><img src="'+ e.target.result +'" data-file="'+f.name+'"/></div></div><div class="picture_overlay"><ul class="picture-overlay-actions"><li class="picture_view"><a class="dz-extraaction tips" href="javascript:void(0);" title="Vizualizeaza"><i class="fa fa-eye"></i></a></li><li class="picture_remove"><a class="dz-remove image-'+nr+' tips" href="javascript:void(0);" title="Sterge" ><i class="fa fa-times"></i></a></li></ul></div></div></li>';
image_holder.append(html);
}
$s('.panel-imagini .no-images').hide();
reader.readAsDataURL(f);
formData.append('foto[]', f);
var codprodus = $s('#product-update').data('product-code');
formData.append('codprodus', codprodus);
});
if(method == 'modify'){
NProgress.start();
jQuery.ajax({
type: 'post',
url: 'index.php?controller=produse_add&method=uploadmultiple',
data: formData,
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
beforeSend: function(data){
$s('.myDropZone').html('<p>Loading...</p>');
},
success: function(data){
var html = '';
$s.each(data, function(k) {
html += '<li class="dz-processing dz-success dz-complete dz-image-preview">';
html += '<div class="documents_drop_file_thumb">';
html += '<div class="picture_menu menu-overlay">';
html += '<div class="picture_thumb_image"><img src="/media/images/'+data[k].image+'"/></div>';
html += '<div class="picture_overlay">';
html += '<ul class="picture-overlay-actions">';
html += '<li class="picture_view"><a class="dz-extraaction tips" href="javascript:void(0);" title="Vizualizeaza"><i class="fa fa-eye"></i></a></li><li class="picture_remove"><a class="dz-remove tips" href="javascript:void(0);" data-dz-remove="' + data[k].product_image_id + '" title="Sterge"><i class="fa fa-times"></i></a></li>';
html += '</ul>';
html += '</div>';
html += '</div>';
html += '</div>';
html += '</li>';
});
$s('.myDropZone').html(html);
},
complete: function(data){
setTimeout(function() {
NProgress.done();
$s('.fade').removeClass('out');
}, 1000);
}
});
}
}
Related
I ran into a problem that I do not close model windows associated with this script from the phone, fa-close button is not pressed. At the same time from the computer everything works fine
function NpcObject(type){
$.ajax({
url: "/do/Npc/",
type: "post",
data: {
type: type
},
success: function (response) {
response = JSON.parse(response);
if(!response['error']){
var tpl = '<div class="model"><div class="header">'+response['title']+'<span onclick=$(".model").remove();><i class="fa fa-close"></i></span></div>';
tpl += '<div class="content-model">';
if(response['type'] == 'pokemarket'){
tpl+= response['html'];
}else if(response['type'] == 'reproduction'){
tpl+= response['html'];
}else if(response['type'] == 'lombard'){
tpl+= response['html'];
}else{
tpl+= '<div class="pit"><input id="pitInput" placeholder="'+Lang.search_pokemon+'" onkeypress=if(event.keyCode==13)nursery("search"); type="text">';
tpl+= '<div class="pok-1">'+response['html'];
tpl+= '';
tpl+= '</div></div></div>';
}
tpl += '</div>';
$("body").append(tpl);
$('.model').draggabilly({
handle: '.header',
containment: true
});
}else{
alert(Lang.error_no_way);
}
}
});
}
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 want to display image from my database which stores the path to the image's location. Following code gives me the image path only in the output. What changes do I need to make in order for image to appear instead of image path?
GetBusinessCategoryList: function () {
debugger;
var data = JSON2.stringify({
});
$.ajax(
{
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'http://localhost:44719/Modules/BusinessCategoryView/Service/BusinessCategoryWebService.asmx/GetAllBusinessCategory',
dataType: 'json',
data: data,
success: function (result) {
alert("ok");
var returnedData = result;
BusinessManagement.BindBusinessCategoryList(returnedData);
},
error: function (error) {
alert("error");
}
});
},
BindBusinessCategoryList: function (data) {
debugger;
var cLst = data.d;
if (cLst.length > 0) {
headElements += '<table id="customerTable" cellspacing="0" cellpadding="0" >';
headElements += '<thead class="sfHeadingone">';
headElements += '<tr><th align="left">Category Image</th>';
;
headElements += '</thead>';
$('#tblGrid').html(headElements);
var i = 0;
if (i === 0) {
bodyElements += '<tbody>';
}
$.each(cLst, function (index, value) {
bodyElements += "<td>" + value.CategoryImage + "</td>";
}
});
Use img to display an image. Pass the image url to the src attribute of the img tag
bodyElements += "<td><img src='" + value.CategoryImage + "'></td>";
I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?
I am currently trying to play a list of .wav file using the VLC plugin and the html object tag in the following manner :
$.each(rdata['results'],function(key,data)
{
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
}
EDIT : The entire function definition :
function fnFormatDetails ( apiUrl, baseUrl )
{
var newRow = "";
var audioUrl;
$.ajax({
type: "GET",
url: apiUrl,
async: false,
contentType : "text/json",
beforeSend:function()
{
image.src = "img/ajax-loader.gif";
},
success: function(data)
{
console.log("success from " + apiUrl);
var rdata = $.parseJSON(data);
$.each(rdata['results'],function(key,data){
audioUrl = baseUrl + data['recordingId'];
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
});
},
error: function(xmlhttprequest,textstatus,message){
if(textstatus === "timeout")
alert("Read timeout. Try again after some time");
else if(xmlhttprequest.status == 500)
alert("Sorry! connection reset by third party server");
},
complete:function(){
image.src = saveSrc;
}
});
newRow = newRow.substring(0,newRow.length - 5);
return newRow;
//------------------------------------------------------------
};
I also have the error function defined as follows :
function error()
{
alert("Resource load error");
}
However, even when the audioUrl throws up an internal server error, onerror does not get fired. Could someone please tell me why this is happening ?
Thanks.
In your success callback here:
success: function(data)
{
console.log("success from " + apiUrl);
var rdata = $.parseJSON(data);
$.each(rdata['results'],function(key,data){
audioUrl = baseUrl + data['recordingId'];
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
});
},
It looks like you are constructing the HTML string in newRow, but you are not actually inserting it into the DOM anywhere. You need to do something like $(document.body).append($(newRow)) (just an example if you wanted to add it to the end of the HTML body).