1

I'm trying to send file content from input file to PHP using AJAX. When I submit the first time, file_content is empty but on all following submit events (without the reloading page) it contains text. It should work from the first click. How can I fix this problem?

<form id="form_file_ajax">
  <div class="row">
    <div class="col-md-6">
      <div class="panel-flat">
        <div class="form-group">
          <div class="row">
            <div class="col-md-12">
              <input type="file" class="file-styled" id="file" accept=".txt" required>
            </div>
          </div>
        </div>
        <div class="text-right">
          <button type="submit" id="btn_submit" class="btn btn-primary">Send<i class="icon-upload position-right"></i></button>
        </div>
      </div>
    </div>
  </div>
</form>
var file_content = '';  

$('#form_file_ajax').on('submit', function(e) {
  e.preventDefault();
  var file = $('input[type=file]')[0].files[0];
  var reader = new FileReader();
  reader.onload = function(e) {
    file_content = reader.result;
  }

  reader.readAsText(file);
  alert(file_content);

  //Send data to server
  var formData = new FormData();
  formData.append('file', $('input[type=file]')[0].files[0]);
  formData.append('id_project', <?= $id_project ?>);
  formData.append('file_content', file_content);


  $.ajax({
    type: 'POST',
    url: '<?= $url_post_file ?>',
    data: formData,
    dataType: 'JSON',
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data.msg);
    },
    error: function(error) {
      console.log(error.responseText);
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
zied123456
  • 255
  • 1
  • 4
  • 17
  • The problem is because `readAsText()` is an asynchronous operation, so `file_content` is set when the `load` event fires, which happens after the first AJAX request completes. Hence the value is set for all following requests. To fix this, make the AJAX request inside the `reader.onload` handler. Although it's worth noting that unless you're specifically doing anything with `file_content` on the client (which you are not currently) then you can avoid the problem and the need for the FileReader by just sending the binary file data in the AJAX request – Rory McCrossan May 17 '19 at 14:12

0 Answers0