I have an issue trying to remove the files which I have passed dropzone.js after calling the database.
When I navigate to the page and upload a new image and then remove it without refreshing the page it all works as expected.
Below is my current upload method
myDropzone.on("success", function (file, response) {
console.log(response);
file.serverId = response;
});
This is what is inside the response after doing console.log(response);
Object { UniqueId="evgopvdjfs1w9sos3jt5"}
Which is correct.
Now when I press F5 and refresh the page I populate dropzone with the following snippet which returns me the image that I've just uploaded.
$.getJSON("/Person/GetPreviews/").done(function (data) {
if (data.Data != '') {
$.each(data.Data, function (index, item) {
var UniqueId = item.ImageName;
var mockFile = {
name: item.ImageName,
serverId: UniqueId // This is what I need to delete the image
};
console.log(mockFile);
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, item.ImageUrl);
myDropzone.files.push(mockFile);
});
}
});
Now when I do console.log(mockFile); the below is shown, again this is correct.
Object { name="evgopvdjfs1w9sos3jt5", UniqueId="evgopvdjfs1w9sos3jt5"}
Now when it comes to removing the file this is my current delete function
removedfile: function (file) {
console.log(file);
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUploadedFile", "Person", new {userId= #Model.UserId})',
data: "id=" + file.serverId['UniqueId'],
dataType: 'html',
});
var ref;
return (ref = file.previewElement) != null ? ref.parentNode.removeChild(file.previewElement) : void 0;
},
Now when I press remove file on the pre populated image from the database, it throws an error on
data: "id=" + file.serverId['UniqueId'],
saying its underfined, I personally cannot see how because both console.logs show the UniqueId it makes me wonder if I'm missing something when I'm pre populating dropzone with the images?
As you can see I have a console.log(file); in the delete function which when hit shows the following
Object { name="evgopvdjfs1w9sos3jt5", UniqueId="evgopvdjfs1w9sos3jt5"}
Can anyone see whats wrong?
So this question is a bit old. I came across it and also found this answer, which helped me:
http://www.stackoverflow.com/questions/24445724/add-existing-image-files-in-dropzone
This particular question was answered here and just points out a mix-up between serverId and UniqueId:
https://github.com/enyo/dropzone/issues/844
Related
I have been struggling with a problem for some time. I cannot understand the reason as it happens in a specific case, not with the others.
I have a javascript function that calls a PHP script to upload a file to the server (standard code, have been using it and works perfectly normally).
function upload_picture(fieldID, success, error) {
var folderName;
switch (fieldID) {
case "pop_drawing":
folderName = "pop_dwg";
break;
case "pop_installation":
folderName = "pop_inst";
break;
case "pop_picture":
folderName = "pop_pict";
break;
}
var file_data = $('#' + fieldID).prop('files')[0];
var form_data = new FormData();
form_data.append('folder', folderName);
form_data.append('file', file_data);
$.ajax({
url: 'dbh/upload.php',
dataType: 'text',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
if (response.indexOf("yüklendi") > 0) {
success();
}
},
error: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
error(response);
}
});
}
The function is called from several points in the code and it works OK except one point. At this particular point when it returns it changes the page URL from
http://localhost/pop/#
to
http://localhost/pop/?pop_drawing=&pop_installation=&pop_picture=Compelis-Logo.jpg&pop_need_special_prod=Hay%C4%B1r&pop_need_application=Hay%C4%B1r&pop_order_made=Evet&pop_approval=4&pop_cost_visible=Hay%C4%B1r#
due to a reason I could not understand. This string in the URL line are some parameters on the web page where I press the button to call the function.
The code which call the function is:
function uploadPopPicture () {
if ($('#pop_picture_label').html() !== 'Seçili dosya yok...') {
upload_picture('pop_picture',
function(){
console.log('Görsel yüklendi...');
},
function(error){
console.log('Error:', error);
});
}
}
Same code (obviously with different parameters) is used elsewhere in the program and works OK.
Any ideas what I might be missing.
Many thanks in advance
A button's default behaviour is "submit". If you don't specify any particular behaviour then that's what it will do. So when clicked it will submit your form, regardless of any JavaScript.
Add the attribute type="button" to your button HTML and that will stop it from automatically submitting the form.
I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
I have an issue using the JQuery-File-Upload plugin. I am using the plugin directly and not through the author's provided html example pages. Basically I have a form with some inputs
one of which is a file input. The first upload works fine but when I attempt a second upload both files are sent (the first one for the second time) when it should only be the second one.
Example:
File 1 is selected.
File 1 is uploaded.
Success.
Using jquery I reset the form with $(FORM_SELECTOR).trigger('reset')
File 2 is selected.
File 1 and file 2 are BOTH uploaded.
Problem.
Now I have two copies of file 1. This is not what I want.
Obviously there isn't much point of using an ajax form upload if it only works once so I assume that there is something I am missing.
Is there a way to reset the file queue?
When examining the data.files object I can see that the files are there after the form
is reset. What can I do to sync the plugin with the input or clear out the data.files.
If I manually clear out the data.files array (via pop or data.files = []) attempting a
second upload does not work.
I init the upload form like this:
$('#file-upload-form').fileupload({
url: 'uploads/upload',
type: 'POST',
dataType: 'json',
multipart: true,
dropZone: null,
formAcceptCharset: 'utf-8',
autoUpload: true,
add: function (e, data) {
fileUploadData = data;
$("#upload-file-btn").click(function () {
data.submit()
.success(function (e, status, data) {
console.log("success response from post", status, data);
var i = '<input id="file-select-input" name="files[]" multiple/>';
$('#file-select-input').replaceWith(i);
})
});
}
});
I have a custom .add event handler, in which I have called .off("click") on my button:
add: function (e, data) {
$('#btnstartupload').off("click");
data.context = $('#btnstartupload')
.click(function () {
data.submit();
$(".fileinput-button").hide();
});
}
I had the same problem and the only way I've managed to solve that was to check in the submit callback if the file was already uploaded. I just check if the file name is included in the array fileNames which I push the current file name before the submission and checks on the next time if the next one is present on the array and if so cancel the submission.
var fileNames = new Array();
$('#uploadfile').fileupload({
submit: function(e, data) ->
var fileName = data.files[0].name;
if ($.inArray(fileName, fileNames) === -1)
fileNames.push(fileName);
else
return false;
});
You can reset inputs quite easy.
If that does not work for you, you might store the file somwhere.
DEMO
$("button#1").click(function(){
//check file
alert($("input").val());
return false;
});
$("button#2").click(function(){
//reset form
$("form")[0].reset();
return false;
});
$("button#3").click(function(){
//replace input
$("input").replaceWith($('<input type="file"/>'));
return false;
});
I ran into the same problem. It's puzzling why the library re-sends previously uploaded files. I tried to destroy it, re-initialize it and clear/reset the actual file input field, but none of them worked.
The solution I came up with is to keep track of all upload attempts by storing file names in an array and checking in the "send" callback if a file has been already uploaded.
Callback:
send: function (e, data) {
var file = data.files[0];
// if we already attempted to upload a file with the same file name
// do not send it in order to avoid duplicates
if (existsInAttemptedUploads(file.name)) {
return false;
}
},
Helper methods:
// list of file names that a user attempted to upload
var attemptedUploads = [];
// adds a file name to the list of attempted uploads
function addAttemptedUpload(fileName) {
attemptedUploads.push(fileName);
};
// removes a given file name from the list of attempted uploads
function removeAttemptedUpload(fileName) {
var index = $.inArray(fileName, attemptedUploads);
if (index > -1) {
attemptedUploads.splice(index, 1);
}
};
// checks if a given file name is in the list of attempted uploads
function existsInAttemptedUploads(fileName) {
var result = $.inArray(fileName, attemptedUploads);
if (result == -1) {
return false;
}
return true
};
Make sure to update the list of attemptedUploads in your "done" and "fail" callbacks and remove a file from the list if it was removed. For example:
done: function (e, data) {
var id = e.target.id;
// List all uploaded files
$.each(data.result.files[0], function (index, file) {
// add the current file name to the list of attempted file names
addAttemptedUpload(file.origFileName);
$('#uploadedFiles').append('<li id="' + file.id + '" data-orig-filename="' + file.origFileName + '">' + file.fileName + ' <a class="removeFile" href="<?php echo $deleteUrl; ?>/' + file.id + '">' + ' Remove</a></li>');
});
},
My code like that, when clicking the Remove link into the multiple file from JSP page, It's OK for IE11, Chrome and Firefox.
function removeFileLink(id) {
var fileName = document.getElementById("import_file_" + id).value.replace(/^.*[\\\/]/, '');
var objFiles = document.getElementsByName("import_fileList");
for(var i=0; i<objFiles.length; i++){
if(objFiles[i].value.replace(/^.*[\\\/]/, '') == fileName) {
$(objFiles[i]).remove();
}
}
document.getElementById("import_form").enctype="multipart/form-data";
document.getElementById("import_form").submit();
return false;
}
Perhaps I'm not understanding this concept (I'm an AJAX/javascript/Web newbie). I'm using the JQuery autocomplete feature and if I specify a small, limited items flat file (suggestions.xml) the function works fine, but when I use an actual production data file (3 MB) of suggestions the script doesn't work at all.
So I created a web service that generates XML based on the characters in the textbox but it appears this JQuery doesn't run on each keypress, rather only when the page first loads. Obviously, for this function to be of any use it needs to fetch results dynamically as the user types into the input field.
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
// this line always sends the default text; not what the user is typing
url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("result").each(function () {
myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
});
}
function setupAC() {
$("input#txtSearch").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.url;
//alert(ui.item.url + " - " + ui.item.label);
}
});
}
});
On the server I expected to see a few requests corresponding to the characters the user is typing into the search box but instead I get a single message:
2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'
My flat file of suggestions appears to be way to large for JQuery to handle and my web service script is never called, except when the page is first loaded.
How do I generate suggestions dynamically as the user is typing in the search box if I can't run back to the database (via my web service) to fetch suggestions as the user is typing?
Ok, I got it all worked out.
On the ASPNET side; I created a form to receive and respond to the AJAX:
Response.ContentType = "application/json";
var term = Request.Form["term"];
var suggestions = GetSuggestions(term); // Database results
if (suggestions.Count < 1)
return;
var serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(suggestions);
On the AJAX side I modified the js function:
$("input#txtSearch").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "Suggestions.aspx",
data: { term: $("input#txtSearch").val() },
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.Name,
value: obj.Url
};
}));
}
});
},
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.value;
}
});
Everything is working as expected now.
Hope this helps someone else who might get stuck trying to figure out JQuery stuff for ASPNET.
I'm using mootools request to push image data to a server to import images. My question is how to determine if an image path is valid before completing the request?
Here's what I have now--
http://jsfiddle.net/sTbFb/1/
function doUpload(){
var remoteFile = document.id('uploadRemote').get('value');
var imageRequest = new Request({
url:'index.php',
method: 'post',
data: 'path='+remoteFile,
onRequest: function() {
console.log(remoteFile);
var myimage = Asset.image(remoteFile,
{
//onError: imageRequest.cancel() // <-- this doesn't work either
onError: this.cancel()
}
);
},
onSuccess: function(response) {
alert(response);
}
}).send();
}
document.id('submit').addEvent('click', function(){
doUpload();
});
I'm trying to use Asset.image to test if a path is truly an image-- then if it's not, to cancel the request. However, it's not working out.
Any hints on what I'm doing wrong? Thanks!
You can't get the path to the selected file from an <input type="file" />. So, you won't be able to load it before you upload it. The best you can do is to check the file extension.
Edit: Perhaps the problem is with this line:
onError: this.cancel()
It should be:
onError: function () {
imageRequest.cancel();
}