I am making a simple plugin that lets users add content to a custom post type. The frontend form includes a few text fields and a file upload field. I am using ajax to submit the form and it's working fine. However, I am trying to make the file upload field to work as well. Once the file has been uploaded, it's value (url) will be added as a custom field.
I am not that familiar with ajax and that's probably why my attempts so far were unsuccessfull. Below is the code I am using so far, minus the file upload stuff:
JS:
(function($) {
$('.btn').on('click', function(e) {
$('.btn').html('<i class="fa fa-spinner fa-pulse"></i>')
e.preventDefault();
var fname = $('#first-name').val();
var lname = $('#last-name').val();
var email = $('#email').val();
var address = $('#address').val();
var phone = $('#phone').val();
var security = $('#security').val();
//var file = $('#entryfile').files[0];
// ajax the results!
$.ajax({
url: ajax.ajax_url,
type: "POST",
dataType : "json",
contentType: false,
processData: false,
data: {
action: 'entry_add',
fname:fname,
lname:lname,
email:email,
address:address,
phone:phone,
nonce: security,
file:file
},
success: function( response ) {
console.log( response );
$('.contest-entry').hide('500', function() {
$('.message > h2').html( response );
$('.message').show('fast');
});
}
});
});
})( jQuery );
PHP:
function ajax_entry() {
check_ajax_referer( 'add-entry-nonce', 'nonce' );
$email = urldecode($_POST['email']);
$fname = wp_strip_all_tags($_POST['fname']);
$lname = wp_strip_all_tags($_POST['lname']);
$addr = wp_strip_all_tags($_POST['address']);
$phone = wp_strip_all_tags($_POST['phone']);
$success = "<i class='fa fa-check'></i> Thanks for joining! You will be reditected to step 2 in a few seconds";
$error = "<i class='fa fa-exclamation-triangle'></i> Looks like something went wrong! Try again maybe?";
if( !empty($email) && !empty($fname) && !empty($lname) && !empty($addr) ) {
$postData = array(
'post_title' => $fname . ' ' . $lname,
'post_type' => 'contestants',
'post_status' => 'draft'
);
$post = wp_insert_post( $postData );
add_post_meta($post, "field_entry_unique", "WTH-".$post);
add_post_meta($post, "field_first_name", $fname);
add_post_meta($post, "field_last_name", $lname);
add_post_meta($post, "field_email", $email);
add_post_meta($post, "field_address", $addr);
add_post_meta($post, "field_status", "pending");
add_post_meta($post, "field_phone", $phone);
if( $post != -1 ) {
//echo json_encode($success);
echo json_encode($file);
} else {
echo json_encode($error);
}
} else {
echo json_encode($error);
}
exit;
}
Can you please help me find a way to make upload work?
EDIT: All solutions I came across so far either do not work (or I just could not make them work), require a second form or break the existing form, thus not allowing for the post to be created. I need some guidance (a few lines of sample code would be great too) as to how I can do this. jQuery is not my strength....
UPDATE: I managed to make this work by using the below. However, while logged out, the upload fails and the console logs a redirect to the login page. Any thoughts?
var formData = new FormData();
formData.append("action", "upload-attachment");
var fileInputElement = document.getElementById("entryfile");
formData.append("async-upload", fileInputElement.files[0]);
formData.append("name", fileInputElement.files[0].name);
formData.append("_wpnonce", upload_nonce);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
}
}
xhr.open("POST","wp-admin/async-upload.php",true);
xhr.send(formData);