简体   繁体   中英

Upload audio file using Ajax and PHP

I am trying to upload an audio file.

What am doing is passing the audio file through Ajax to PHP where the upload and other insert to my database will be done.

After passing it through Ajax, my PHP page does not see the audio file.

<script type="text/javascript">
$(function () {

  $('form').on('submit', function (e) {

    e.preventDefault();

    document.getElementById("load").style.display = "block";
    textarea = $('#editor-one').html();
    var formData = new FormData($(this)[0]);
    formData.append("content", textarea);

    $.ajax({
      type: 'post',
      url: 'verimg.php?ins=newmu',
      data: formData,

      cache: false,
      contentType: false,
      processData: false,
      success: function(data){
        document.getElementById("load").style.display = "none";
        //alert(textarea);
        jQuery('#get_result').html(data).show();
      }
    });
  });
});

  </script>

Here is my PHP code:

if(!isset($_FILES['file'])){
  echo '<div class="alert alert-warning">
          <strong>Warning!</strong> Please select an audio
        </div>';
}else{
  $uploaderror='';
  $name = ucfirst($_POST['name']);
  $artist = $_POST['artist'];
  $content = $_POST['content'];
  $genre = $_POST['genre'];

  $validator = new FormValidator();
  $validator->addValidation("name","req","Please fill in Music Name");
  $validator->addValidation("category","req","Please Select Artist");
  $validator->addValidation("category","req","Please Select Genre");
}

I always get "Warning! Please select an audio".

I have made changes to your formData. In your php code you are trying to check the 'file' key in your global $_FILES variable but in your formData variable the audio file isn't attached to any 'key'. Hope it works :)

<script type="text/javascript">
 $(function () {

$('form').on('submit', function (e) {

  e.preventDefault();

  document.getElementById("load").style.display = "block";
  textarea = $('#editor-one').html();
  var formData = new FormData();
  formData.append("file", e.target.files[0]);
  $.ajax({
    type: 'post',
    url: 'verimg.php?ins=newmu',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data)
    {
        document.getElementById("load").style.display = "none";
        //alert(textarea);
        jQuery('#get_result').html(data).show();
    }
  });

});

});

</script>

Try to add enctype='multipart/form-data' to your form tag.
;)

A long painfull Reference is here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM