JSFiddle - React, Tailwind, and code Playground

by Mubasshir Pawle

HTML

<!DOCTYPE html>
<html>

  <head>
    <title>
      Async file upload with jQuery
    </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
  </head>

  <body>
    <div align="center">
      <form method="post" action="" enctype="multipart/form-data" id="myform">

        <div>
          <input type="file" id="file" name="data[Model][file]" />
          <input type="text" id="_file" name="data[Model][_file]" />
          <input type="button" class="button" value="Upload" id="but_upload">
        </div>
      </form>
    </div>
  </body>

</html>

JavaScript

$('input[type="file"]').change(function() {
			  var element = $(this);
			  var element_ = $('#' + element.attr('id'));

			  var files = $('#file')[0].files;
			  if (files.length > 0) {
			    var fd = new FormData();
			    fd.append('file', files);

			    $.ajax({
			      url: 'upload.php',
			      type: 'post',
			      data: fd,
			      contentType: false,
			      processData: false,
			      success: function(urls) {
			        element_.val(urls.join(','));
			        element.val('');
			      },
			    });
			  }
			});