0

Can you please take a look at this code and let me know what I am missing/ doing wrong here on sending two inputs of a form by using jQuery Ajax and formData?

Technically I would like to have a preview of images and do some updates on them like removing or re-ordering and after that upload them to the server but what I am getting is this error

Uncaught TypeError: Illegal invocation

on jQuery

var value = isFunction(valueOrFunction) ?
  valueOrFunction() :
  valueOrFunction;

Here is the code

function previewImages() {

  var $preview = $('#preview').empty();
  if (this.files) $.each(this.files, readAndPreview);

  function readAndPreview(i, file) {

    if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
      return alert(file.name + " is not an image");
    } // else...

    var reader = new FileReader();

    $(reader).on("load", function() {
      $preview.append($("<img/>", {
        src: this.result,
        height: 100
      }));
    });

    reader.readAsDataURL(file);

  }

}

$('#file-input').on("change", previewImages);

$("#btn-upload").on("click", function() {

  var fd = new FormData($('form')[0]);
 
  var request = $.ajax({
    type: "POST",
    url: "upload.php",
    data: fd,
    cache: false,
    beforeSend: function() {

    }
  });

  request.done(function(data) {

  });

  request.fail(function(jqXHR, textStatus) {
    console.log("Request failed: " + textStatus);
  });
});
body{
  padding:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <form id="uploader" action="#" method="post">
    Package Name
    <input id="package" type="text" />
    <br /> 
    Package Images <input id="file-input" type="file" multiple>
  </form>
</div>

<div class="well">
  <div id="preview"></div>
</div>

<div class="well">
  <button class="btn btn-success" id="btn-upload">
    Now Upload
  </button>
</div>
Pedram
  • 15,766
  • 10
  • 44
  • 73
JJ BOBO
  • 111
  • 11
  • `src: this.result,` That's not how you get the result, look here -> https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload – Keith Feb 04 '18 at 21:52
  • @Keith events are generally bound to their target. – Kaiido Feb 05 '18 at 06:06
  • You need to tell jQuery not to process the data by adding the option `processData: false` in your `$.ajax` param. – Kaiido Feb 05 '18 at 06:08

0 Answers0