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?

4
  • Possible duplicate of stackoverflow.com/questions/166221/… Commented Jan 27, 2016 at 17:58
  • 1
    look into FormData(), it let's you spoof file uploads in ajax. Commented Jan 27, 2016 at 18:11
  • While stackoverflow.com/questions/166221/… 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. Commented Jan 27, 2016 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. Commented Jan 28, 2016 at 17:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.