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;