user3655266 user3655266 - 10 months ago 51
HTTP Question

How to send http body data on an ajax post

$(document).delegate('form', 'submit', function(event) {
var $form = $(this);
var id = $form.attr('id');
// ...
/* stop form from submitting normally */

// /* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );

var timeId = parseInt(id.substring(11));

var formData = new FormData($("#"+id)[0]);
console.log("time id of form is "+timeId);
url: url,
method: "POST",
dataType: 'json',
data: formData,
processData: false,
contentType: false,
success: function(result){},
error: function(er){}


I am sending the image file from a html form using ajax post. How can i send additional data as a body of this http post

Answer Source

To pass the additional data from the DOM elements, you can use the serialize() as well.


If you want to get the images, you should go with like this.


<input type="file" name="file" accept="image/*" id="image">

Multiple files can be appended by using each

var data = new FormData();
$.each($('#image')[0].files, function(i, file) {
    data.append('file-'+i, file);

Pass addition data in formData


//Program a custom submit function for the form
  //disable the default form submission
  //Other data
  //File data
<script src=""></script>
<form enctype="multipart/form-data" id="test" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <input type="hidden" name="id" value="10">
  <input type="file" name="file" id="image">
  <input type="submit">