I have a standard form with fields. One of those fields is a file upload. The form is processed via ajax and in the success block, IF there are attached files, I need to make another ajax call to upload the file. This is where I’m struggling. If an upload needs to be done, I execute the if/ block, perform ajax, then on ajax success, redirect. In the /else block, I don’t need to perform any ajax, so I can immediately redirect. I don’t like having this redirect twice as it is not DRY. I know I can instead use a function in each of these places, then only have the redirect once, but that still seems to violate the DRY standard since I’m still calling the function twice.
Is there a better way to write this?
if (files.length > 0) {
readFile(files[0],function(filestring){
var fileObj = new Object();
fileObj.file = filestring.split(";base64,")[1];
fileObj.fullFileName = document.getElementById("file").files[0].name;
fileObj.fileName = fileObj.fullFileName.split(".")[0];
fileObj.ext = fileObj.fullFileName.split(".")[1];
fileObj.leadid = resp.leadid;
doAjax(fileObj,endpoints.file).then(function(resp){
window.location.href = "returnURL";
});
});
}else{
window.location.href = "returnURL";
}
I cannot think of a better/cleaner way to write this and I am not sure how to search for this on Google, since I’m not sure what the correct terminology would be to describe this problem.