nsikak
nsikak

Reputation: 111

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".

Upvotes: 0

Views: 2879

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

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

A long painfull Reference is here.

Upvotes: 0

Abdul Samad
Abdul Samad

Reputation: 441

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>

Upvotes: 1

Related Questions