2

I'm attempting to upload an audio file via AJAX form.

Here is my HTML in the profile-edit template.

<form method="post" id="my_upload_form" action="" enctype="multipart/form-data">
  <input type="file" name="file" id="my_file_input" accept="audio/*">                                      
  <input type="submit" class="btn-submit btn-sumary" value="upload audio file" name="submit" id="my_audio_submit">                                      
  <div id="my_error_report"></div>                                  
</form>

Here is my jQuery:

$('#my_upload_form').submit(function () {

    var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';
    var html = '<strong><em> ' + '<p style="' + css + '">' + '*';
    var endHtml = '</p></em></strong>';

    var formData = new FormData();
    var fileArray = jQuery('#my_file_input').prop('files');

    if(fileArray.length > 0) {
        var theTrack = fileArray[0];
        formData.append("music", theTrack);
    } else {
      jQuery('#my_error_report').html( html + 'no track selected' + endHtml );
      return false;
    }

    $.ajax({
      url: '/wp-admin/admin-ajax.php',
      type: 'POST',
      // async: false,
      data: {
          action      : 'my_track_upload',
          some_data   : formData
      },
      // dataType: 'text'
      }).success( function( data ) {
          /* You win! */
          alert('ajax was called success');
      }).fail( function( data ) {
          /* You lose, show error */
          alert('ajax was called failure');
    });
    return false;  
}); 

Finally here is my plugin code:

add_action('wp_ajax_my_track_upload', 'my_track_upload');
function my_track_upload()
{
  die('hello');
}

Problem (more to come): Why is the page refreshing? I return false in the jQuery 'submit' event.

************************EDIT********************

I changed my code to the following and it works now, though I'm not sure specifically where the problem was.

... ... ...

var theTrack = fileArray[0];
        formData.append('action', 'musistic_track_upload');
        formData.append("music", theTrack);
enter code here

... ... ...

$.ajax({
  url: '/wp-admin/admin-ajax.php',
  type: 'POST',
  data: formData,
  enctype: 'multipart/form-data',
  contentType: false,
  processData: false,
  datatype: "script",
  beforeSend: function() {
    jQuery('#my_error_report').html('');
  }
}).complete(function( data ) {
  jQuery('#my_error_report').html( html + data.responseText + endHtml );
  jQuery('#my_audio_submit').val("Upload Audio File", function() {
    jQuery(this).prop('disabled', false);
  });
});

return false;
  • Have you checked your javascript console.log using developer tools in the case there's javascript errors? Have you tried returning false at the top of your submission listener to narrow down the issue? – Howdy_McGee Jan 25 '16 at 19:24
  • The error is: Uncaught TypeError: Illegal invocation Could it be that the AJAX call wants a string in the some_data parameter? I've seen many examples using the same method I have above. – Keenan Diggs Jan 25 '16 at 19:28
  • Double check $ is set to jQuery. By default it is not. – jgraup Jan 25 '16 at 19:30
  • Thanks for your comment jgraup. I open my js file with 'jQuery(document).ready(function($) {', so I don't think that's the error. I also have another function that disables the submit button when it is clicked. – Keenan Diggs Jan 25 '16 at 19:32
  • Ah yes, I've run into this same issue recently. It has nothing to do with WordPress ( so it's off topic here ) but the issue is that you need to append your action to your formData() object so that the only thing that gets passed into data is: data: formData. No brackets, no name identifier just exactly like that. You can append your action exactly like you're appending music. Hopefully that works for you! – Howdy_McGee Jan 25 '16 at 19:35
4

Try using preventDefault(), it's a jQuery function for preventing default actions called by the browser.

First you should call an event handler by firing up your submitter. You can do this as follow:

$('#my_upload_form').submit(function (event) {

After catching a submit and giving an event with it, you should prevent the default refresh of a browser:

event.preventDefault();

Now your code will look as follow:

$('#my_upload_form').submit(function (event) {

    event.preventDefault();

    var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';
    var html = '<strong><em> ' + '<p style="' + css + '">' + '*';
    var endHtml = '</p></em></strong>';

    var formData = new FormData();
    var fileArray = jQuery('#my_file_input').prop('files');

    if(fileArray.length > 0) {
        var theTrack = fileArray[0];
        formData.append("music", theTrack);
    } else {
      jQuery('#my_error_report').html( html + 'no track selected' + endHtml );
      return false;
    }

    $.ajax({
      url: '/wp-admin/admin-ajax.php',
      type: 'POST',
      // async: false,
      data: {
          action      : 'my_track_upload',
          some_data   : formData
      },
      // dataType: 'text'
      }).success( function( data ) {
          /* You win! */
          alert('ajax was called success');
      }).fail( function( data ) {
          /* You lose, show error */
          alert('ajax was called failure');
    });
});

BTW: Always try to place preventDefault() on top of the function, it should prevent the default action before anything else is done.

  • Good suggestion. I just fiddled with the AJAX call until it worked. To my shame, I still don't fully understand why. For those interested in further reading on preventDefault and 'return false' this is a good thread: stackoverflow.com/questions/1357118/… – Keenan Diggs Jan 27 '16 at 23:14
1

I was missing a crucial line in my AJAX query. Without this option, the call fails, and the pages refreshes.

processData: false,
  • 1
    I tried everything else, but this DID it immediately. I had a form action and an Ajax call listening for the 'click' event. This was third-party software and when I tried to change to 'submit' nothing would get submitted. Doing processData: false, magically solved everything. – Mo Alsaedi Oct 24 '18 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.