Home > Software design >  JavaScript if/else statement, one has ajax, the other does not, but both should redirect to same pla
JavaScript if/else statement, one has ajax, the other does not, but both should redirect to same pla

Time:12-14

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.

In case you need to see it, here is the doAjax function.

function doAjax(data,url){
  return  $.ajax({
            url: url,
            cache: false,
            method: "post",
            dataType:"json",
            data: data
        });
}

Here is the readFile function

function readFile(files,callback){
  var reader = new FileReader();
  reader.readAsDataURL(files);
  reader.onload = function (e) {
    callback(reader.result);
  }
  reader.onerror = function (error) {
      console.log('Error: ', error);
  };  
}

CodePudding user response:

How about something like this?

doAjax = function(files, endpoints) {
    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;

          return resp;
      });
    }

     return [];
}

doAjax(files, endpoints).then(function(resp) {
    window.location.href = "returnURL";
});

EDIT: I was reading your post again, уоu say 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 The question is, where do you perform validation? Validation has to be done along with the form on the server side. A hacker may be able to upload files without the having success back from the server. This is best done using one call, уоu send the attached files (if they exist), validate the form, if success then уоu store the files, if not then уоu throw an error, then redirect the user when уоu get the response whether they attached files or not.

Using Axios this would look something like this:

let form_data = new FormData();
form_data.append('data_to_validate', data);

if (files.length > 0) {
    form_data.append('attachment', myFiles.files[0]);
}

axios({
    url: '/api',
    method: 'post',
    data: form_data,
    headers: {'content-type': 'multipart/form-data'}
})
.then(response => {
    window.location.href = response.returnURL;
})
.catch(error => {
});
  • Related