thanks for taking a look at my question.
The Problem
I need to be able to an upload feature image(thumbnail) that is associated with a post, the website that is being worked on has the ability to make posts from the front-end of the website.
Custom code implemented
in the post submission form I'm using a input element of type file:
<form class="compose-post-form" method="POST" enctype="multipart/form-data">
...
<input type="file" name="featured" id="featured">
...
</form>
The data is being sent to the backend on form submit with jQuery AJAX:
$.ajax({
type: 'post',
url: t_ajax_url.ajax_url,
data: $this.serialize() + "&tri_post_content="+article_content+"&article="+article,
beforeSend: function () {
is_sending = true;
},
success: function (data) {
//window.location.replace(get_homepage_url+'trisine');
var fd = new FormData();
var file = $('#featured').val();
fd.append("featured", file);
fd.append('action', 'thumbnail_up');
jQuery.ajax({
type: 'POST',
url: t_ajax_url.ajax_url,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
},
error: function(xhr, status, error) {
console.log(status);
}
});
This is the code that saves the thumbnail, for now I'm just testing with a post ID of 22:
add_action( 'wp_ajax_thumbnail_up', 't_thumbnail_up' );
function t_thumbnail_up(){
$uploaddir = wp_upload_dir();
$file = $_FILE['featured'];
$uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );
move_uploaded_file( $file['tmp_name'] , $uploadfile );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'menu_order' => $_i + 1000
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
update_post_meta(22, '_thumbnail_id',$attach_id);
set_post_thumbnail( 22, $thumbnail_id );
exit();
}
The results are that something get's uploaded but it seems to only be the folders name, which is November's month number, the folder isn't actually created on the server:
Any help on how I can get this to work will be highly appreciated.
Use this functions to handle files from ajax.
<?php
$thumbnail = $_FILES[ 'featured' ];
$thumbnail_id = media_handle_sideload( $thumbnail, $post_id );
set_post_thumbnail( $post_id, $screenshot_id );
Related
I am stuck since couple of days on the same issues, i hope someone can help with this. I have tried mutiple functions i found on stackoverflow but it seems i am doing something completely wrong!
I need to upload a file to wordpress library with a form submission on the frontend using AJAX.
This is the form:
function shortcode__new_upload_file() {
/**
* #var WP_User $current_user
*/
$current_user = $GLOBALS['current_user'];
ob_start(); ?>
<form id="form-upload" method="POST" enctype="multipart/form-data">
<div class="custom-file">
<input type="file" name="imagefile" class="custom-file-input" id="imageFile">
<label class="custom-file-label" for="imageFile">Choose file</label>
</div>
<textarea class="form-control" id="imageMessage" name="message"></textarea>
<button type="submit" class="btn btn-outline-secondary submit" id="process-upload"><?php _e('Save'); ?></button>
<button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
</form>
<?php
$html = ob_get_clean();
return $html;
}
// Ads shortcode so you can use the form anywhere you want.
add_shortcode( 'new_upload_file', 'shortcode__new_upload_file' );
AJAX call:
jQuery(document).ready(function($){
//$('#process-upload').on('click', function(e){
$("#form-upload").on('submit',function(e){
e.preventDefault();
var el_form = $('#form-upload')
//var data = new FormData();
//data.append('action', 'new_upload_file');
//data.append('imageFile', $('input[type=file]')[0].files[0] );
//data.append('message', $('#imageMessage').val() );
// If form is valid run function
new_upload_file()
// Ajax request.
function new_upload_file() {
$.ajax({
url: localized_new_upload_file.admin_ajax_url,
type: 'POST',
//contentType: false,
enctype: 'multipart/form-data',
//processData: false,
//data: data,
dataType: 'json',
data: {
action: 'new_upload_file', // Set action without prefix 'wp_ajax_'.
form_data: el_form.serialize()
},
cache: false,
success: function(response){
console.log(response);
window.alert('Done!');
}
});
}
});
});
function upload_file_callback(){
// get entered form data
parse_str( $_POST['form_data'], $form_data );
$postarr = array();
// merge all array and make new array, now get data for each input like following: $form_data[LUBUVNA_PREFIX.'from']
$postarr = array_merge( $postarr, $form_data );
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
//$uploadedfile = isset($_FILES['imagefile']) ? $_FILES['imagefile'] : '';
$uploadedfile = $form_data['imagefile']; //$_FILES['imagefile'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$feedback = "File is valid, and was successfully uploaded.\n";
var_dump( $movefile);
} else {
/**
* Error generated by _wp_handle_upload()
* #see _wp_handle_upload() in wp-admin/includes/file.php
*/
$feedback = print_r($movefile, true);
}
// send email with details
$headers = [
'MIME-Version: 1.0',
'From: myemailfrom#hotmail.com',
'Content-Type: text/html; charset=UTF-8'
];
$headers = implode("\r\n", $headers);
wp_mail('myemailto#gmail.com','Script Ran','<br>FEEDBACK:<br>'.$feedback. '<br>FORM Array:<br>' . print_r($postarr, true) ,$headers);
}
//add_action('wp_ajax_nopriv_new_upload_file', 'upload_file_callback');
add_action( 'wp_ajax_new_upload_file', 'upload_file_callback' );
So the form data is showing up in the email like following after form submission:
FEEDBACK:
Array ( [error] => Specified file failed upload test. ) NASH TEXT:
FORM Array:
:Array ( [message] => car )
I am not getting the data of the imagefile field. and that's why i guess i am getting an error Specified file failed upload test.
Whats wrong with my function.. i have by the way tried $_FILES / $_POST but there is something i am missing.
EDIT
JS File
jQuery(document).ready(function($) {
//$("#form-upload").submit(function(e){
$("#form-upload").on('submit',function(e){
e.preventDefault();
var $this = $(this);
var formData = new FormData( $this[0] );
formData.append('action', 'new_upload_file');
//formData.append('_nonce', $('input[name*="my_token"]') ).val();
//formData.append('_nonce', $this.closest('form').find('.nonce').val();
formData.append('_nonce', $(this).find('input[name*="my_token"]').val() );
// Ajax request.
$.ajax({
url: localized_new_upload_file.admin_ajax_url,
type: 'POST',
data: { 'form_data' : formData },
contentType: false,
//enctype: 'multipart/form-data',
cache: false,
processData: false,
success: function(response){
console.log(response);
window.alert('Done!');
}
});
return false;
});
});
FORM
<form id="form-upload" method="POST" enctype="multipart/form-data">
<div class="custom-file">
<!--<input type="file" name="imagefile" class="custom-file-input" id="imageFile" accept="image/*">-->
<input type="file" name="imagefile" class="custom-file-input" id="imageFile">
<label class="custom-file-label" for="imageFile">Choose file</label>
<!--<input name="my_token" class="nonce" value="<?php //echo wp_create_nonce("my_token"); ?>" type="hidden">-->
<?php wp_nonce_field( SECURE_AUTH_SALT, 'my_token' ) ?>
</div>
<textarea class="form-control" id="imageMessage" name="message"></textarea>
<button type="submit" class="btn btn-outline-secondary submit" id="process-upload"><?php _e('Save'); ?></button>
<button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
</form>
PHP
function script__new_upload_file() {
wp_enqueue_media();
wp_enqueue_script(
'new_upload_file',
get_stylesheet_directory_uri(). '/ajax-file-upload.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script( 'new_upload_file', 'localized_new_upload_file', array(
'admin_ajax_url' => admin_url( 'admin-ajax.php' ),
//'security' => wp_create_nonce( 'my-special-string' )
));
}
// Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL.
add_action( 'wp_enqueue_scripts', 'script__new_upload_file' );
function upload_file_callback(){
// get entered form data
parse_str( $_POST['form_data'], $form_data );
$postarr = array();
// merge all array and make new array, now get data for each input like following: $form_data[LUBUVNA_PREFIX.'from']
$postarr = array_merge( $postarr, $form_data );
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
//$uploadedfile = isset($_FILES['imagefile']) ? $_FILES['imagefile'] : '';
$uploadedfile = $form_data['imagefile']; //$_FILES['imagefile'];
//print_r($uploadedfile);
// die();
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$feedback = "File is valid, and was successfully uploaded.\n";
var_dump( $movefile);
} else {
/**
* Error generated by _wp_handle_upload()
* #see _wp_handle_upload() in wp-admin/includes/file.php
*/
$feedback = print_r($movefile, true);
}
// send email with details
$headers = [
'MIME-Version: 1.0',
'From: myemailfrom#hotmail.com',
'Content-Type: text/html; charset=UTF-8'
];
$headers = implode("\r\n", $headers);
wp_mail('myemailto#gmail.com','Script Ran','<br>FEEDBACK:<br>'.$feedback. '<br>FORM Array:<br>' . print_r($postarr, true) ,$headers);
}
add_action('wp_ajax_nopriv_new_upload_file', 'upload_file_callback');
add_action( 'wp_ajax_new_upload_file', 'upload_file_callback' );
When using the FormData object in $.ajax, you pass it directly as the data field
jQuery(document).ready(function($) {
//$("#form-upload").submit(function(e){
$("#form-upload").on('submit',function(e){
e.preventDefault();
var formData = new FormData( this );
formData.append('action', 'new_upload_file');
//formData.append('_nonce', $('input[name*="my_token"]') ).val();
//formData.append('_nonce', $this.closest('form').find('.nonce').val();
formData.append('_nonce', $(this).find('input[name*="my_token"]').val() );
// Ajax request.
$.ajax({
url: localized_new_upload_file.admin_ajax_url,
type: 'POST',
data: formData, //<----- Pass the formdata object only
contentType: false,
cache: false,
processData: false,
success: function(response){
console.log(response);
window.alert('Done!');
}
});
return false;
});
});
In PHP
$_FILES['imagefile'] will give you access to the file
$_POST['message'] will give you access to the textarea text
$_POST['_nonce'] will give you access to the nonce
$_POST['action'] will give you access to the action
I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.
The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.
I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.
The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.
Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.
/**
* Handle ajax file upload to media library.
*
* #since 1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'], 'wpday_dz_protect')) {
// Including file library if not exist
if (!function_exists('wp_handle_upload')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
// Uploading file to server
$movefile = wp_handle_upload($_FILES['file'], ['test_form' => false]);
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $post->ID,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
// Adding file to media
$attachment_id = wp_insert_attachment($attachment, $filename);
// If attachment success
if ($attach_id) {
require_once ABSPATH . 'wp-admin/includes/image.php';
// Updating attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
}
$message['error'] = 'false';
$message['data'] = wp_get_attachment_url($attach_id);
} else {
$message['error'] = 'true';
$message['data'] = $movefile['error'];
}
wp_send_json($message);
}
}
add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
add_action('wp_ajax_nopriv_wpday_dz', 'wpday_dz_ajax_upload_handle');
EDIT:
Have tried:
$id = get_the_ID();
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $id,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
Still returns unattached
I downloaded WP Dropzone and had a look at the code. AFAICT the function you are working on is called via AJAX, once a file is dropped/uploaded. In that case, there is no "post" in the current request - you're in an AJAX file unrelated to any post.
So the question becomes how to get the ID of the post that called the current AJAX request. I found this SO answer which answers that:
$url = wp_get_referer();
$post_id = url_to_postid( $url );
I need to send the param imgName (together with the picture) to php in order to change the "image default name to imgName"
var imgName = "30";
file_data = $('#pictureInput').prop('files')[0];
form_data = new FormData();
form_data.append('file', file_data);
var newdata = {imgName: imgName, form_data: form_data};
var json = JSON.stringify(newdata);
$.ajax({
url: 'editImage.php',
cache: false,
contentType: false,
processData: false,
data: json,
type: 'post',
success: function(data){
console.log(data);
}
});
php
(i need help with my php)
move_uploaded_file($_FILES['file']['tmp_name'], 'pictures/' . $imgName . '.png');
Try as follows:-
$imgName = $_POST['imgName'];
move_uploaded_file($_FILES['file']['tmp_name'], 'pictures/' . $imgName . '.png');
$imgName = tempnam('/pictures', '');
unlink($imgName);
move_uploaded_file($_FILES['file']['tmp_name'], $imgName);
I think using tempnam() is good for you. You do not need to worry about randomness.
change your js code as
var formData = new FormData();
var imagefile = document.querySelector('#pictureInput');
if (imagefile.files && imagefile.files[0]) {
formData.append("file", imagefile.files[0]);
}
and in ajax
data: formData,
I am writ plugin for WordPress. It sends a link to the images on the PHP file (Ajax).
The array consists of 10 photos.
obj.photos.push({ img_url: img_url, source: source, photo_text: photo_text, tag: tag });
var data_insert = {
action: 'instapin_insert',
data: obj
};
$.ajax({
type: 'POST',
url: '/wp-content/plugins/instapin/ajax.php',
data: data_insert,
});
Next, the file takes a picture and the script loads to the cloud with Google (Google Drive).
<?php
session_start();
session_write_close();
require_once('../../../wp-config.php');
global $service;
if(class_exists('INSTAPIN'))
{
$instapin = new INSTAPIN();
}
$google_drive = get_option('instapin_drive');
$photos_array = $_POST['data']['photos'];
// Создаём объект записи
$instapin_post = array(
'post_title' => 'Название записи',
'post_content' => '',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(0)
);
// Вставляем запись в базу данных
$post_id = wp_insert_post( $instapin_post );
if($google_drive == 'on'){
$folder = get_option('google_upload_folder');
$found = false;
$files = $service->files->listFiles();
foreach ($files['items'] as $item) {
if ($item['title'] == $post_id) {
$folder_insert_photo = $item['id'];
$found = true;
break;
}
}
if($found == false){
$file = new Google_Service_Drive_DriveFile();
//Setup the Folder to Create
$file->setTitle($post_id);
$file->setDescription('Photo folder: post_id - ' . $post_id);
$file->setMimeType('application/vnd.google-apps.folder');
//Set the ProjectsFolder Parent
$parent = new Google_Service_Drive_ParentReference();
$parent->setId( $folder );
$file->setParents(array($parent));
//create the ProjectFolder in the Parent
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
$folder_insert_photo = $createdFile->id;
$instapin->insertPermission($service, $folder_insert_photo, 'id', 'anyone', 'reader');
}
$count = 1;
$photo = new Google_Service_Drive_DriveFile();
$parent_folder = new Google_Service_Drive_ParentReference();
foreach($photos_array as $item){
if($count == 40){
break;
}
$img_url = strtok($item['img_url'], '?');
$image_url = str_replace("s150x150/", "", $img_url);
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
$wp_filetype = wp_check_filetype( $filename, null );
$MimeType = $wp_filetype['type'];
$seo_name = $item['tag'] . '_' . $count . '.jpg';
//Setup the Folder to Create
$photo->setTitle($seo_name);
$photo->setDescription('Photo: ' . $image_url);
$photo->setMimeType($MimeType);
$parent_folder->setId( $folder_insert_photo );
$photo->setParents(array($parent_folder));
// Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true'
$createdPhoto = $service->files->insert($photo, array(
'data' => $image_data,
'mimeType' => $MimeType,
'uploadType'=> 'multipart'
));
$instapin->insertPermission($service, $createdPhoto->id, 'id', 'anyone', 'reader');
$filePath = "GoogleDrive/{$folder_insert_photo}/{$seo_name}";
$fullFile = "https://googledrive.com/host/{$folder_insert_photo}/{$seo_name}";
print_r($fullFile);
$count++;
}
}
?>
But when I send an AJAX post to upload 10 photos, all admin panel and front. Nothing can be done and go until the download is complete (the script works).
But when I post to download 10 photos, all admin panel and front crashes (hangs). Nothing can be done and go until the upload is finished (the script works).
How to make this multi-tasking? So the admin panel and front continue to work, and the script is working in the background.
I've made a script which uses $.ajax and FormData to pass two form objects to PHP. One form object is a text and the other is a file.
It worked well as a stand-alone script. However, after I added it to Wordpress, as a plugin, it keeps giving me "Uncaught TypeError: Illegal invocation".
I can't afford to serialize the formdata, simply because then I won't be able to pass the file to the callback function in PHP.
JS involving FormData before ajax call:
var fd = new FormData();
var file = jQuery(this).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
This part above is 100% correct.
Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
This is incredibly frustrating since it worked perfectly fine outside of Wordpress. I've tried de-registering Wordpress' jQuery and enqueueing the latest jQuery version, but it made no difference.
To recap:
1) Ajax/jQuery is refusing to pass a form object to PHP
2) Can't serialize the object because I need to preserve the file object
3) Script works outside of Wordpress
4) Tried updating to the newest jQuery version, no change
try this :
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var fd = new FormData();
var file = jQuery(document).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
fd.append('action', 'fiu_upload_file');
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
php
function fiu_upload_file(){
var_dump($_FILES);
exit();
}
add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');
I managed to do it. The code works on the latest version of Wordpress (4.9.4)
First of all, I'm using XMLHttpRequest to send the data and not the jQuery ajax. This means that you can adapt it to just pure JS.
Notice the xhttp.setRequestHeader("enctype","multipart/form-data"); which was essential to pass the FormData using this method.
JS:
var user_id = $('#user_id').val();
var picture = $('#userPic')[0].files[0];
console.log(picture);
if( picture && typeof picture !== undefined ) {
if ( picture['size'] > 1000000 ) {
alert('The Profile Pic can\'t be larger than 1Mb.');
return;
}
if ( picture['type'].indexOf('image') == -1 ) {
alert('The uploaded file needs to be an image.');
return;
}
var data = new FormData();
data.append('user_id', user_id);
data.append('userPic', picture);
// console.log(data);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('Receive:' + this.responseText);
}
};
xhttp.open("POST", location.origin + "/wp-content/themes/search-and-go-child/ajax/upload_user_profile_pic_ajax.php", true);
xhttp.setRequestHeader("enctype","multipart/form-data");
xhttp.send(data);
}
The PHP part is also extremely useful since it requires the files needed to manipulate the received data with the WP core functions.
Here you will also find the code to upload an attachment using the WP core functions.
PHP:
// error_reporting(-1);
// ini_set('display_errors', 'On');
$path = $_SERVER['DOCUMENT_ROOT'];
require_once($path.'/wp-load.php');
require_once( '/home/s24t06b21lk5/public_html/wp-includes/template-loader.php' );
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/image.php');
require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/file.php');
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/media.php');
$user_id = $_POST['user_id'];
$picture = $_FILES['userPic'];
var_dump($user_id);
var_dump($picture);
$response = array();
if( isset($picture['name']) && $picture['name'] ) {
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$picture['name'] = preg_replace( '/[^0-9a-zA-Z.]/', '', basename( $picture['name'] ) );
// Upload the file
$upload_overrides = array( 'test_form' => false );
$upload_result = wp_handle_upload($picture, $upload_overrides);
// echo '<pre>'; print_r($upload_result); echo '</pre>' ;
if( $upload_result['url'] ) {
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $upload_result['url'],
'post_mime_type' => $picture['type'],
'post_title' => $picture['name'],
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload_result['file'] );
if( $attach_id ) {
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_result['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
// Update the usermeta table with the uploaded avatar
if( !update_user_meta($user_id, 'wp_user_avatar', $attach_id ) || !update_user_meta($user_id, 'wp_zfgrf5v7rw_user_avatar', $attach_id) ) {
$response['result'] = FALSE;
$response['message'] = "The uploaded image could not be associated with the User ID in the database.";
}
else {
$response['result'] = TRUE;
}
}
else {
$response['result'] = FALSE;
$response['message'] = "Wordpress attachment post for the user's image could not created.";
}
}
else {
$response['result'] = FALSE;
$response['message'] = "The file couldn't be uploaded. Check the permissions.";
}
}
die( json_encode($response) );
Thank you.
Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)
$('#form').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "fiu_upload_file");
$.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(data){
if(data.error == 'true') {
$('.msg').html(data.true);
}
else {
$('.msg').html(data.false);
// your code if you want an action ...
};
}
});
});
and php for only the files
foreach ($_FILES as $file) :
if($file['error'] == UPLOAD_ERR_NO_FILE) :
continue;
endif;
$valid_ext = array( 'jpg' , 'jpeg' , 'png' , 'doc' , 'docx' , 'pdf' , 'xls' , 'xlsx');
$extension_upload = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ( in_array($extension_upload,$valid_ext) ) :
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$msg_true = 'Upload ok ';
else :
$msg_error = 'Upload error';
endif;
endforeach;
$result = !isset($msg_error);
$msg = array();
if($result) :
$msg['error'] = 'true';
$msg['true'] = $msg_true;
else :
$msg['error'] = 'false';
$msg['false'] = $msg_error;
endif;
header('Content-Type: application/json');
echo json_encode($msg);
I added
dataType: 'json'
and it helps.
Full listing of your code of Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
dataType: 'json',
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
here some modified code in case you have multiple data and multiple files
var fd = new FormData();
var data = jQuery('#yourformID').serializeArray();
jQuery.each(data,function(key,input){
fd.append(input.name,input.value);
});
var file = jQuery(document).find('input[type="file"]');
jQuery.each(jQuery(file), function(i, obj) {
jQuery.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
fd.append('action', 'fiu_upload_file');