user2653179
user2653179

Reputation: 423

HTML + JQuery: Empty form values

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"

Upvotes: 0

Views: 232

Answers (2)

dlebech
dlebech

Reputation: 1839

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.

Upvotes: 1

dhruvin
dhruvin

Reputation: 807

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

Upvotes: 1

Related Questions