1

I am trying to add some animation while a type-file input is processing the file, I decided to use jQUery's ajax method to send the form data.

I noticed that the beforeSend method works, but not with the success method, but instead, the error method contains all the response sent by my node server. I tried looking for similiar question but none of them work for me.

JS:

fileForm.on('submit', function(e) {
    e.preventDefault();
    let formData = new FormData();
    formData.append('file', $('#input-file').prop('files')[0]);
    $.ajax({
      url: this.action,
      dataType: 'script',
      cache: false,
      contentType: false,
      processData: false,
      beforeSend: () => {
        console.log('loading');
      },
      success: function(response) {
        console.log(response); // Not logging anything
        setTimeout(() => {
          console.log('succeded: ' + response);
        }, 500);
      },
      error: (err) => {
        console.log(err); // This logs the response
      },
      data: formData,
      type: this.method.toUpperCase()
    });
  });

Node.JS:

router.post('/image', upload.single('file'), async (req, res) => {
  if (req.session.passport !== undefined) {
    try {
      console.log(req.file, req.body);
      const query = {_id: req.session.passport.user};
      const user = await modelAct(userModel, query, 'findOne');
      // const opt = {
      //   query: query,
      //   data: {
      //     $set: {
      //       avatar_path: req.file.path
      //     }
      //   }
      // };
      // await modelAct(userModel, opt, 'updateOne');
      res.status(200).json({fileData: req.file});
    } catch(err) {
      console.log(err);
      if ((typeof err.message == 'string')) {
        res.sendStatus(err.message);
      } else {
        res.sendStatus(500);
      }
    }
  } else {
    res.sendStatus(401);
  }
});

Here's a screenshot of the network tab

Kemal Dwiheldy
  • 409
  • 1
  • 4
  • 14

0 Answers0