I am trying to create form and submitting this with ajax. So the page wont reload. I don't have a lot of experience with ajax and I am trying to find as much information as I can.
Right now in my code I can sbmit form without reloading. But I have a field for uploading files. I know It is a bit different to do this and I also found some examples but so far no luck. For example Ajax file upload in Wordpress - can't pass FormData
Right now I have My Ajax code like this:
Ajax
(function($) {
jQuery(document).ready(function() {
// when user submits the form
jQuery(document).on('submit', '.form-assignment', function(event) {
var error_elm = jQuery('.ajax-error');
var response_elm = jQuery('.ajax-response')
// var widgetId = grecaptcha.reset(container);
error_elm.html('');
response_elm.html('');
// prevent form submission
event.preventDefault();
var form_elm = jQuery(this);
var url = form_elm.data('url');
var action = form_elm.data('action');
var form_data = new FormData();
var data = {
action: action,
form_data : form_data
};
// add loading message
response_elm.html('Loading...');
jQuery.ajax({
type : 'POST',
url : url,
data : data,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
dataType : 'json',
async : true
}).success(function(response) {
error_elm.html('');
response_elm.html('');
if(response.status !== 'success') {
// something went wrong
if(response.message) {
error_elm.html(response.message);
return;
}
// don't know ?
}
// success!!
// log data
console.log(response);
// display data
response_elm.html(response.message);
$("#form-assignment").trigger("reset");
grecaptcha.reset();
}).error(function(response) {
error_elm.html('');
response_elm.html('');
error_elm.html(response.statusText);
});
});
});
})( jQuery );
My form:
<div class="ajax-error" style="color: red;"></div>
<form class="form-assignment" name="form_assignment" id="form-assignment"
method="post" enctype="multipart/form-data"
data-url="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ) ?>" data-action="form_submit1">
<label>name:</label>
<input type="text" name="customer-field-text"pattern="[a-zA-Z0-9 ]+" placeholder="<?php echo $field->label ?>" size="40"/>
<label>file upload</label>
<input type="file" name="customer-field-upload" id="customer-field-upload"
multiple="false"/>
</form>
Right now this is how far I got. This is not my full form I have already added nonce and other required settings for sequrity. When I check input file It keep displaying error message that the field is empty.
My form handler
function handle_form_submission (){
global $wpdb;
$response = array(
'status' => 'error',
'message' => '',
);
parse_str($_POST['form_data'], $form_data);
//global $error;
$error = new WP_Error();
if (empty($_POST['customer-field-name']) ) {
$error->add('empty','Name is required.');
}
if (empty($_POST['customer-field-upload']) && empty($_FILES["customer-field-upload"]["name"])) {
$error->add('empty','select an file.');
}
if ( !empty( $error->get_error_codes() ) ) {
$error_messages = $error->get_error_messages();
$error = '';
foreach($error_messages as $error_message) {
$error .= '<p>'.$error_message.'</p>';
}
$response['message'] = $error;
wp_send_json( $response );
wp_die();
}
$name = sanitize_text_field( $form_data["customer-field-name"] );
$upload = sanitize_text_field( $form_data["customer-field-upload"] );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
media_handle_upload( 'customer_field_upload', $form_data['post_id'] );
}
add_action( 'wp_ajax_form_submit1', 'handle_form_submission' );
// ajax hook for non-logged-in users: wp_ajax_nopriv_{action}
add_action( 'wp_ajax_nopriv_form_submit1', 'handle_form_submission' );
So My question is What can I do or add in my ajax or form handler to get file upload submit with Ajax working. Any suggestion, advice or some existing example that are familiar will be appreciated. I am practicing with WordPress and Ajax that is how far I got.
I have tried to use FormData but still no luck so far.