If you’re wondering How to Upload a File in WordPress Using Ajax, you’ve come to the right place. We’ll show you how to upload a file using a frontend form and jquery ajax without installing a plugin from the WordPress media library.
Create HTML Form
<h2>Upload a File</h2>
<form method="post" class="cxc_upload_form"enctype="multipart/form-data">
<div class="cxc_image_url"></div>
<input type="file" name="file" required />
<input type="submit" id="cxc_upload_file" name="cxc_upload_file" value="Upload"/>
</form>
Ajax submission Get jQuery code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on('click', '#cxc_upload_file', function(e){
e.preventDefault();
var cxc_form = new FormData();
var file = jQuery(document).find('input[type="file"]');
var cxc_individual_file = file[0].files[0];
if( cxc_individual_file == undefined ){
alert('Please Include a Image');
}else{
cxc_form.append("file", cxc_individual_file);
cxc_form.append('action', 'cxc_upload_file_data');
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: cxc_form,
contentType: false,
processData: false,
success: function( cxc_response ){
if( cxc_response != '' && cxc_response.success ){
jQuery('.cxc_upload_form')[0].reset();
alert('successfully uploaded an image');
jQuery( '.cxc_upload_form .cxc_image_url' ).html( '<img style="max-width:400px;width:100%;height:auto;margin-bottom:10px;" src="' + cxc_response.cxc_image_url + '">' );
}else{
alert('Image not uploaded');
}
}
});
}
});
});
</script>
Ajax in WordPress/PHP code
<?php
/* Upload File Data With Ajax*/
add_action('wp_ajax_cxc_upload_file_data', 'cxc_upload_file_data');
add_action('wp_ajax_nopriv_cxc_upload_file_data', 'cxc_upload_file_data');
function cxc_upload_file_data(){
$cxc_upload_dir = wp_upload_dir();
$cxc_success = false;
$cxc_messages = '';
if ( ! empty( $cxc_upload_dir['basedir'] ) ) {
$cxc_user_dirname = $cxc_upload_dir['basedir'].'/cxc-images/';
$cxc_user_baseurl = $cxc_upload_dir['baseurl'].'/cxc-images/';
if ( ! file_exists( $cxc_user_dirname ) ) {
wp_mkdir_p( $cxc_user_dirname );
}
$cxc_filename = wp_unique_filename( $cxc_user_dirname, $_FILES['file']['name'] );
$cxc_success = move_uploaded_file( $_FILES['file']['tmp_name'], $cxc_user_dirname .''. $cxc_filename);
$cxc_image_url = $cxc_user_baseurl .''. $cxc_filename;
if( !empty( $cxc_success ) ){
$cxc_success = true;
}else{
$cxc_success = false;
}
$cxc_messages = array( 'success' => $cxc_success, 'cxc_image_url' => $cxc_image_url );
wp_send_json( $cxc_messages );
}
}
Output
Was this article helpful?
YesNo