1

Due Diligence

Just to be clear I have searched for the answer to this question and found these great questions that unfortunately do not help me.

Submit form including file upload via jQuery ajax
jQuery AJAX submit form
jquery using ajax to send data and save in php
jQuery AJAX submit form

Setup

I have a system for pulling form values and posting them via ajax. A simple snippet may look something like:

  // Values
  var url = '/ajax/my/controller'
  var values = myStuff.getFormValues($form);

  // Post
  $.post(url, values, function($response)
  {
    if ($response['status'])
    {
      // Success
    }
    else
    {
      // Validation error.
    }
  }, 'json');

My getFormValues functions runs some custom processing to make sure I only send the information I need so I am keen on keeping it. It is probably similar to the jQuery 'serialize' function but much simpler and with custom processing.

The Problem

My get form values function basically does a $('selector').val() to get the form values. Which does not upload the file fields. It returns a fake path like C:\fakepat\filename.png. This of course will not work. I need to actually submit the file as part of the ajax post operation.

The question

Without switching to jquery serialize (since it doesn't fully support files anyway) and without using any other libraries such as jquery form, How do I obtain the file from the file field and post it using ajax?

Simplified, how do I simulate the behavior of a standard file field submit with an ajax post?

Community
  • 1
  • 1
danielson317
  • 3,121
  • 3
  • 28
  • 43
  • Possible duplicate of http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Charlotte Dunois Jan 27 '16 at 17:58
  • 1
    look into `FormData()`, it let's you spoof file uploads in ajax. – dandavis Jan 27 '16 at 18:11
  • While http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously is helpful it does not tell me how to obtain the file and add it to a post values array, only how to post all form values as a whole. I'm experimenting now but I don't think it qualifies as a duplicate. – danielson317 Jan 27 '16 at 18:29
  • Sure enough FormData works. I used a simplified version of the what @CharlotteDunois referenced. But this is really just a work-around. I still want to be able to obtain a file without having to wrap it in a barely supported FormData class. I have a hard time believing this was impossible to do until IE10 came out. – danielson317 Jan 28 '16 at 17:17

0 Answers0