Aware there are a few questions around this topic, I have been searching through them most of this evening trying to find a solution to my problem. This is the first time I have worked on such task.
I am trying to upload a file via AJAX in WordPress. I have set up AJAX in WordPress and the connection works fine, until I try to pass the form data at which stage I am getting a 'bad request' error and no other information other than this.
The AJAX callback function in WordPress is simple enough:
add_action( 'wp_ajax_nopriv_calendar_process', 'calendar_process' );
add_action( 'wp_ajax_calendar_process', 'calendar_process' );
function calendar_process() {
echo "worked";
die();
}
My front end form looks like this:
<form method="post" class="custom-cal-form">
<input type="file" accept=".ics" name="custom-calendar" id="custom_cal_file" />
<button class="submit-ajax">Update Calendars</button>
</form>
And my AJAX call looks like this:
jQuery( document ).on( 'click', '.submit-ajax', function(e) {
e.preventDefault();
var file_data = jQuery('#custom_cal_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
console.log(form_data);
jQuery.ajax({
url : calendarprocess.ajax_url,
type : 'post',
processData: false,
contentType: false,
data : {
action : 'calendar_process',
post_id : 'test',
calendar : form_data
},
success : function( response ) {
jQuery('.ajax-response').html( response );
}
});
});
I was originally getting the error
Can only call FormData.append on instances of FormData
Until I looked around at some questions and added
processData: false, contentType: false,
To my form and now the full error I get is:
Failed to load resource: the server responded with a status of 400 (Bad Request)
Which of course signals that WordPress is not happy.
Really hoping someone can add some insight into this? Thanks in advance.