Brayen H. K
Brayen H. K

Reputation: 31

Post Excel file through AJAX

Is there any way to send an Excel file through an AJAX POST request? I've tried this, but I don't know how to wrap the file through the request. Can AJAX do this?

<form id='file-import' method="POST" enctype="multipart/form-data">
  <meta name="csrf-token" content="{{ csrf_token() }}" />
  <label>Choose File</label>
  <div class="form-group">
    <input type="file" name="file" required="required">
  </div>
  <button type="submit" class="">Import</button>
</form>
$(document).ready(function() {
  console.log('run');
  $('#file-import').submit(function(e) {
    e.preventDefault();
    let form_data = new FormData($(this)[0]);
    console.log(form_data);
    $('#content').hide();
    $('#page-loader').fadeIn();
    $.ajax({
      url: '/test/post',
      type: 'POST',
      data: 'form_data',
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      dataType: 'json',
      success: function(data) {
        console.log('success');
      },
      error: function() {
        console.log('error');
      }
    });
    $('#page-loader').fadeOut();
    $('#content').show();
  });
});

Upvotes: 3

Views: 2089

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337666

You have two main problems with this AJAX request. Firstly you're sending the string literal 'form_data', not the actual value held in the form_data variable. You need to remove the quotes around it.

Secondly, you need to add the contentType and processData properties to the AJAX request when sending a FormData object, and both their values should be false.

Also note that you need to call fadeOut() and show() when the AJAX request finishes. Where you have those calls right now means that you show the loader and then immediately hide it as the request is async. To make this work properly, move the calls in to a complete handler in the AJAX settings. Try this:

$('#file-import').submit(function(e) {
  e.preventDefault();
  let form_data = new FormData($(this)[0]);
  var $content = $('#content').hide();
  var $pageLoader = $('#page-loader').fadeIn();

  $.ajax({
    url: '/test/post',
    type: 'POST',
    data: form_data,
    contentType: false,
    processData: false,
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    dataType: 'json',
    success: function(data) {
      console.log('success');
    },
    error: function() {
      console.log('error');
    },
    complete: function() {
      $content.show();
      $pageLoader.fadeOut();
    }
  });
});

Upvotes: 1

Related Questions