I'm working on a project where registred users can upload file to a specific post type. For a more fluid navigation, I'm making this whole part with Ajax, so the page never reloads.
However I'm having a hard time trying to make a <input type="file">
work.
Here's my code so far:
Markup
<?php
// Start Loop and current meta of the post
?>
<form class="update_post" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID(); ?>">
<label for="new_value_1_for_<?php echo get_the_ID(); ?>">Value 1</label>
<input type="text" name="new_value_1_for_<?php echo get_the_ID(); ?>" id="new_value_1_for_<?php echo get_the_ID(); ?>" value="" required>
<label for="new_value_2_for_<?php echo get_the_ID(); ?>">Value 2</label>
<input type="text" name="new_value_2_for_<?php echo get_the_ID(); ?>" id="new_value_2_for_<?php echo get_the_ID(); ?>" value="" required>
<label for="file_upload_for_<?php echo get_the_ID(); ?>">File Upload</label>
<input type="text" name="file_upload_for_<?php echo get_the_ID(); ?>" id="file_upload_for_<?php echo get_the_ID(); ?>" value="" required>
<input type="submit" name="submit" class="button1 submit_update_post" value="Send">
<div class="progress_bar"></div>
</form>
<?php
// End Loop
?>
jQuery
$(".update_post").submit(function(){
var formData = new FormData(this);
$.ajax({
type: "POST",
dataType: "json",
url: "url_to_php_file",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
// Show a loader animation
},
success: function(data) {
// Hide the loader animation and update the info
},
error: function() {
// Display error message
}
});
return false;
});
php
$post_id = $_POST['post_id'];
$value_1 = $_POST['new_value_1_for_'.$post_id.''];
$value_2 = $_POST['new_value_2_for_'.$post_id.''];
// Update the Post Meta
update_post_meta($post_id, 'value_1', $value_1);
update_post_meta($post_id, 'value_2', $value_2);
// Upload the file
$file_upload = wp_upload_bits($_FILES['file_upload_for_'.$post_id.'']['name'], null, file_get_contents($_FILES['file_upload_for_'.$post_id.'']['tmp_name']));
if (isset($file_upload['error']) && $file_upload['error'] != 0) {
echo '<script type="text/javascript">
alert("' . $file_upload['error'] .'");
</script>';
update_post_meta($post_id, 'file_upload', "");
}
else {
update_post_meta($post_id, 'file_upload', $file_upload);
}
$file_uploaded = get_post_meta($post_id, 'file_upload', true );
// Output
$array = array(
"value_1" => $value_1,
"value_2" => $value_2,
"file_url" => $file_uploaded['url'],
);
print json_encode($array);
Everything but the file upload works.
Is there something I'm missing?
Thank you so much.