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"
3
  • If you have a look here api.jquery.com/serializeArray you will find that file inputs are not serialized. Commented Sep 11, 2013 at 10:59
  • I saw that use in here 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? Commented Sep 11, 2013 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: developer.mozilla.org/en-US/docs/Web/Guide/… Commented Sep 11, 2013 at 16:04

2 Answers 2

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});

Sign up to request clarification or add additional context in comments.

2 Comments

But the id isn't part of the form. It's a global parameter. I still get [] after serializeArray().
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.
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.

Comments

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.