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

On submit upload files to server WordPress

  • SOLVED

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'].
'/order-quotes/'.$randomID;
if (!file_exists($user_dirname)) {
wp_mkdir_p($user_dirname);
}
}
move_uploaded_file($_FILES['file']['tmp_name'][$i], $user_dirname.
'/'.$filename);
}
$dataSubmission = $wpdb - > insert(
$table_name, array(
'order_id' => $order_id
, 'user_id' => $randomID
)
, array(
'%d', '%d
)
);

return true;
exit();
}

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


frontend code

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

Answers (2)

2021-05-16

Bob answers:

These articles will help you.

https://artisansweb.net/ajax-file-upload-in-wordpress/

https://www.phpkida.com/upload-file-using-ajax-in-wordpress/

https://www.ibenic.com/wordpress-file-upload-with-ajax/


Shoeb mirza comments:

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

2021-05-19

Rempty answers:

Check if your form have the parameter
enctype="multipart/form-data"

try to debug your code using
print_r($_FILES['file'])
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]));
}
wp_die();
}