Trying to use admin-ajax.php
to upload image from front-end form. I’m keep getting 0
with below code I have and not sure how to debug this or where it goes wrong.
I have HTML input file
<input type="file" name="wh_image_upload" id="wh_image_upload" multiple="false" />
and localized script for AJAX request
$img_nonce = wp_create_nonce('image_upload_nonce');
wp_localize_script( 'ajax-script', 'ajax_image', array( 'ajax_url' => admin_url( 'admin-ajax.php' )) );
and PHP function
function write_here_featured_image_upload() {
var_dump($_FILES);
die();
}
add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' );
add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' );
JS
// Featured image upload AJAX
$("#wh_image_upload").change(function(){
var userFile = new FormData();
var fileInput = $( "#wh_image_upload" )[0].files[0];
//console.log(fileInput);
userFile.append("file", fileInput);
userFile.append("action", "write_here_img_upload");
$.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: userFile,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
},
success: function(data) {
console.log("Image Uploaded! " + data);
}
});
});
I get a AJAX success message with response 0
. Image Uploaded! 0
Update
I updated my working code.