user3655266 user3655266 - 2 months ago 8
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 */
event.preventDefault();

// /* 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);
console.log(formData);
$.ajax({
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

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

$('form#id').serialize();

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

console.log($('#image').get(0).files[0]);

<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

data.append("timeId",10000);

//Program a custom submit function for the form
$("form#test").submit(function(event){
  //disable the default form submission
  event.preventDefault();
  //Other data
  console.log($(this).serialize());
  //File data
  console.log($('#image').get(0).files);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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">
</form>

Comments