Reputation: 1145
I'm trying to send a form after a file has been uploaded successfully, and then clean that form to let the user upload another file, the problem is that If i upload the first time, the form get sent once, If I upload the second time, the form get sent two time while it should be sent one time only , Upload another file for 3rd time, the form get sent 3 times .
I want the form to be sent one time whenever the user upload a new file , no matter how many times he does that .
Here's my code :
$("#send-pc").off('click').on("click",function(){
var data = {};
console.log('hi')
myDropzone.processQueue()
test_cpt = 0;
myDropzone.on("queuecomplete",function(file){
$("#form-pc").serializeArray().map(function(x){data[x.name] = x.value;})
data["filename"] = myDropzone.files[0].name
data["token"] = oauthToken
console.log(data["filename"])
test_cpt = test_cpt + 1
$.post("/add-docs-pc",data).done(function(resp){
if(resp == "200"){
alert("Vos documents on été ajouté à la platforme")
reset_form()
myDropzone.removeFile(file)
}
else{
console.log("ERROR")
}
})
});//queuecomplete Callback
});
When I check test_cpt
when I upload another file for a second time it's 2, it should be one, so I'm sure that the event "queuecomplete" is being called recursively . How can I achieve what I want and getting out of this loop ? Is there way to kill that event without destroying my object ?
I'm looking for a general JS method not specifically related to DropeZone JS
Upvotes: 1
Views: 120
Reputation: 370729
It looks like every time something is submitted, that outer click function runs - and every time that outer click function runs, a new handler is attached to myDropzone
here:
myDropzone.on("queuecomplete",function(file){
You need to remove the handler once the response gets sent out, so that subsequent clicks, uploads, and queuecomplete
s won't trigger the handler attached previously. Either declare the handler as a function and use .off
at the end, or simply use jQuery's .one
such that the handler gets unbound automatically once it's called:
function queueCompleteHandler(file) {
$("#form-pc").serializeArray().map(function(x){data[x.name] = x.value;})
data["filename"] = myDropzone.files[0].name
data["token"] = oauthToken
console.log(data["filename"])
test_cpt = test_cpt + 1
$.post("/add-docs-pc",data).done(function(resp){
if(resp == "200"){
alert("Vos documents on été ajouté à la platforme")
reset_form()
myDropzone.removeFile(file)
}
else{
console.log("ERROR")
}
});
// Remove the handler if you used `on` instead of `one`:
// myDropzone.off("queuecomplete", queueCompleteHandler);
}
myDropzone.one("queuecomplete", queueCompleteHandler);
Upvotes: 3