user2636664
user2636664

Reputation: 411

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below

<script>    
$("#submit1").click(function(){
  testSubmit(event);
});

function testSubmit(event) {
  event.preventDefault();
  var data = new FormData();
  var file_data = $('input[type="file"]')[0].files; // for multiple files
  for(var i = 0;i<file_data.length;i++){
    data.append("file_"+i, file_data[i]);
  }

  var other_data = $('#form_id').serializeArray();
  $.each(other_data,function(key,input) {
    data.append(input.name,input.value);
  });

  $.ajax({
    url: 'test.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
      alert(data);
    }
  });
}  
</script>

Here submit1 is a button on form form_id

This code is working fine, however the below line

data.append("file_"+i, file_data[i]);

as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?

Thanks for reading this

Upvotes: 0

Views: 1527

Answers (1)

Samosa
Samosa

Reputation: 845

If you are using jQuery then why not something like this

$('input[type="file"]').each(function($i){
  data.append($(this).prop("id"), $(this)[0].files[0]);
});

Entire Code :-

<script>    
  $("#submit1").click(function(){
    testSubmit(event);
  });

  function testSubmit(event) {
    event.preventDefault();
    var data = new FormData();

    $('input[type="file"]').each(function($i){
      data.append($(this).prop("id"), $(this)[0].files[0]);
    });

    var other_data = $('#form_id').serializeArray();
    $.each(other_data,function(key,input){
      data.append(input.name,input.value);
    });

    $.ajax({
      url: 'test.php',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      type: 'POST',
      success: function(data){
        alert(data);
      }
    });
  }   
</script>

Upvotes: 3

Related Questions