Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

On submit upload files to server WordPress


I'm trying to submit AJAX form along with multiple files. Though I'm able to store data in DB, but my files are not being uploaded to server. Can anyone help where I'm going wrong?

Here is my functions.php code

function savedata() {
$randomID = uniqid();
$order_id = rand(1000, 9999);
global $wpdb;
$table_name = 'wp_order_quotes_real';
$countfiles = count($_FILES['file']['name']);
for ($i = 0; $i < $countfiles; $i++) {
$filename = $_FILES['file']['name'][$i];
$upload_dir = wp_upload_dir();
if (!empty($upload_dir['basedir'])) {
$user_dirname = $upload_dir['basedir'].
if (!file_exists($user_dirname)) {
move_uploaded_file($_FILES['file']['tmp_name'][$i], $user_dirname.
$dataSubmission = $wpdb - > insert(
$table_name, array(
'order_id' => $order_id
, 'user_id' => $randomID
, array(
'%d', '%d

return true;

add_action('wp_ajax_savedata', 'savedata');
add_action('wp_ajax_nopriv_savedata', 'savedata');

frontend code

$("body").on('click', '#formSubmit', function(e) {
const data = previewAllFields(true);
type: "POST",
url: ajaxURL,
data: {
action: "savedata",
success: function(data) {
alert('Your order has been saved into our database!');
error: function (error) {
console.log(error, '===error===');

Answers (2)


Bob answers:

These articles will help you.

Shoeb mirza comments:

I've done some research based on the similar articles like above. I seem to stuck somewhere


Rempty answers:

Check if your form have the parameter

try to debug your code using
and view the structure of the $_FILES array

Shoeb mirza comments:

Almost achieve with one of the articles which Bob has mentioned. However, whenever I'm uploading multiple files, it is generating multiple folders and uploading file separately in that.

global $randomFolder;
$randomFolder = '';

function file_upload_callback() {
add_filter( 'upload_dir', function( $arr ) use( &$_filter){
if ($randomFolder == '') {
$randomFolder = substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 16);
$arr['path'] = $arr['basedir'].'/order-quotes/'.$randomFolder;
return $arr;
for($i = 0; $i < count($_FILES['file']['name']); $i++) {
$upload = wp_upload_bits($_FILES['file']['name'][$i], null, file_get_contents($_FILES['file']['tmp_name'][$i]));