0

Just looking for some advice really. I have a small form on my website which i'm building:

  • Name
  • Email
  • Number
  • CV (attachment)

I have done forms before, however with the added attachment i'm not sure how to go about it.

Im used to using jQuery's serialize function. Is there something similar i can use to post within my Ajax call? I cant seem to find much info on the web..

Planty
  • 63
  • 7

1 Answers1

1

For AJAX requests, you cannot really use .serialize() functions. You need to use FormData(). You can also put a progress bar. We need to check for the support first:

function supportAjaxUploadWithProgress() {
  return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();

  function supportFileAPI() {
    var fi = document.createElement('INPUT');
    fi.type = 'file';
    return 'files' in fi;
  };

  function supportAjaxUploadProgressEvents() {
    var xhr = new XMLHttpRequest();
    return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
  };

  function supportFormData() {
    return !! window.FormData;
  }
}

The next step is to submit the form using AJAX:

var form = document.getElementById('form-id');
var formData = new FormData(form);

You have to have these HTML:

var form = document.getElementById('the-form');
form.onsubmit = function() {
  var formData = new FormData(form);

  formData.append('file', file);

  var xhr = new XMLHttpRequest();
  // Add any event handlers here...
  xhr.open('POST', form.getAttribute('action'), true);
  xhr.send(formData);

  return false; // To avoid actual submission of the form
}
<form id="the-form" action="/upload/path" enctype="multipart/form-data">
  <input name="file" type="file">
  <input type="submit" value="Upload" />
</form>

More info: Ridiculously simple Ajax uploads with FormData.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252