1

I have a form that I want to submit using AJAX. The form lets you upload a picture as an attachment, among other fields. Now using pure rails it works just fine, and the AJAX post function I have set up also works...until I try to upload this image file. It just submits without the file as if I did not attach it. What is the correct flow for this? the ajax function

function postInstrument() {
  $("form#new_instrument").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: `http://localhost:3000/users/${userId}/instruments`,
      data: $(this).serialize(),
      dataType: "json",
      success: document.getElementById("new-instrument-form-div").innerHTML = 'Instrument Added!'
    })
  })

}
Morks
  • 284
  • 3
  • 15

2 Answers2

1

The solution was just to wrap my form in a FormData object.

Morks
  • 284
  • 3
  • 15
  • I'm facing the exact same problem. Can you elaborate on your solution? – stratis Oct 31 '21 at 11:01
  • For anyone still wondering how to do this just type: ```const formData = new FormData($('#myform')[0])``` and use ```formData``` as the `$.ajax` `data` attribute. – stratis Oct 31 '21 at 20:18
0

You are using .serialize for your image data. And that is not possible. This link is by far the best for you to read about file uploading https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications

function FileUpload(img, file) {
  const reader = new FileReader();  
  this.ctrl = createThrobber(img);
  const xhr = new XMLHttpRequest();
  this.xhr = xhr;

  const self = this;
  this.xhr.upload.addEventListener("progress", function(e) {
        if (e.lengthComputable) {
          const percentage = Math.round((e.loaded * 100) / e.total);
          self.ctrl.update(percentage);
        }
      }, false);

  xhr.upload.addEventListener("load", function(e){
          self.ctrl.update(100);
          const canvas = self.ctrl.ctx.canvas;
          canvas.parentNode.removeChild(canvas);
      }, false);
  xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
  reader.onload = function(evt) {
    xhr.send(evt.target.result);
  };
  reader.readAsBinaryString(file);
}

And here How can I upload files asynchronously?

sasy solutions
  • 179
  • 1
  • 9