Sunday, September 23, 2018

File form submission by AJAX and PHP

Step 1: First have a look at the HTML form:
<form id="form" id="file-form" name="file_form" method="post" enctype="multipart/form-data">
<input type="file" id="file-input" name="file_input" value="" />
<input type="submit" id="submit-btn" class="submit_btn" name="submit" value="Upload" />
<span class="validation-msg"></span>
</form>

<button id="main_submit_btn">Upload</button>

Step 2: Then handle this form by JS(jQuery) code:
// Jquery handle submission of file
(function ( $ ) {
  $(document).ready(function(){
    $(".submit_btn").css({'visibility':'hidden'});
    $("#main_submit_btn").click(function(event){
      // event.preventDefault();
      var fd = new FormData();
      var file = $('#file-form').find('input[type="file"]');
      var myFile = file[0].files[0];
     
      if (myFile === undefined) {
$('.validation-msg').text('Please select file!');
      }
      else {
        $('.validation-msg').text('');
// disabled the submit button
        $("#main_submit_btn").prop("disabled", true);
        $('.spinner').css({"visibility":"visible"});
        $.ajax({
  url: process.php, // url to process
  data: fd,
  processData: false,
  contentType: false,
  dataType: 'json',
  type: 'POST',
  success: function (response) {
    // Upload succefull
    processFDH(fd, FDHfile);
  },
  error: function (e) {
    $("#main_submit_btn").prop("disabled", false);
    $('.spinner').css({"visibility":"hidden"});
  }
});
      }
  });
})(jQuery);

Step 3: process.php
if (isset($_FILES)) { 
   //
  if (check_upload_error($uploaded)) {
    echo json_encode("Error uploading file: " . $uploaded->get_error_message());
  }
  else {
    ajax_xml_import($file_content['name'], $location);
    echo json_encode('Import Done!');
  }
}
else {
  echo json_encode('Please upload some files!');

}

No comments:

Post a Comment

Suomen kieli (Imperfekti)

In Finnish, the imperfekti is the past tense that describes actions that happened in the past, like the English simple past (e.g., "I ...