0

I'm trying to send the form data + additional parameter "id" to the server (Python, Google App Engine).

My form:

 <form method="post" action="/" id="form1" runat="server" enctype='multipart/form-data'>
       <div class="fileButtons">
       <input type='file' id="imgInp" name="imgInp" accept="image/*"/>
        <input type="submit" id="submit" name="action" value="Send"/>
        <input type='button' id='remove' name="remove" value="Remove" />
        </div>
    </form>

Javascript function:

$( '#form1' ).submit(function( event ) {
  event.preventDefault();

  var data = $(this).serializeArray();
  data.push({name: 'id', value: id});

  $.ajax({
    type: 'POST',
    url: '/set_image',
    data: data,
    dataType: 'json',
    success: function( resp ) {
      console.log( resp );
    }
  });
});

data only receives the id.

When debugging it with Firebug: I get the following:

this form#form1

  imgInp input#imgInp property value = "2.jpg" attribute value = "null"

  remove input#remove attribute value = "Remove"
user2653179
  • 393
  • 1
  • 6
  • 21
  • If you have a look here http://api.jquery.com/serializeArray/ you will find that file inputs are not serialized. – makmonty Sep 11 '13 at 10:59
  • I saw that use in here http://stackoverflow.com/a/6627996/2653179. If it can't be done this way, how do I add the additional data to the form and send it all in a POST request? – user2653179 Sep 11 '13 at 11:59
  • You might want to have a look to FormData object. With it, you can send files and other stuff via an AJAX call. Here some examples: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects?redirectlocale=en-US&redirectslug=Web%2FAPI%2FFormData%2FUsing_FormData_Objects – makmonty Sep 11 '13 at 16:04

2 Answers2

1

may be you are attempting it wrong when you try to push the values in the data array.

Instead of writing var data = $(this).serializeArray(); data.push({name: 'id', value: id});

just try this

var data = $(this).serializeArray(); data.push({id : $("#imgInp").val});

dhruvin
  • 787
  • 1
  • 6
  • 11
  • But the id isn't part of the form. It's a global parameter. I still get [] after serializeArray(). – user2653179 Sep 11 '13 at 10:49
  • in that case, answer below from @dlebech is accurate to your problem. But submitting a file input parameter will not work on IE9 and older version of IE browsers. – dhruvin Sep 13 '13 at 04:16
1

Try serializing your array like this instead:

var data = new FormData($(this)[0]);

For more information see this answer and notice that it will not work in older versions of Internet Explorer. If you need cross-browser compatibility, your cannot submit files through ajax.

Community
  • 1
  • 1
dlebech
  • 1,817
  • 14
  • 27