Ended up doing it like this:
In functions.php:
//SEND IMAGE INTO WORDPRESS
function new_attachment(){
//echo 'talking to new_attachement in functions.php';
if(
! wp_verify_nonce( $_POST['client-file-upload'], 'add_attachement' ) //adding a layer of security by verifying a nonce that was set in the addrecipe.php form field
){
wp_nonce_ays( '' ); //Display “Are You Sure” message to confirm the action being taken. A = are Y = You S = Sure. Don't know if needed here.
}
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$myfiles = $_POST["async-upload"];
$id = media_handle_upload('async-upload', 0); //post id of Client Files page
$attachment_url = wp_get_attachment_url($id);
unset($myfiles);
if ( is_wp_error($id) ) {
$errors['upload_error'] = $id;
$id = false;
}
if ($errors) {
echo "<p>There was an error uploading your file.</p>";
} else {
echo $attachment_url;
}
exit();
}
add_action('wp_ajax_add_attachement','new_attachment'); //add an image file
Javascript:
jQuery('#file-form').submit(
function (e) {
e.preventDefault();
let mydata = new FormData(this);
mydata.append('action', 'add_attachement');
jQuery.ajax({
url: adminAjaxURL,
type: 'POST',
data: mydata,
processData: false,
contentType: false,
success: function (result) {
console.log(result);
jQuery('#imageURLs').val(result);
//$("#div1").html(str);
}
})
});
PHP and HTML:
<form id="file-form" enctype="multipart/form-data">
<p id="async-upload-wrap">
<label for="async-upload">Lataa kuva</label>
<input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Lataa" name="html-upload">
</p>
<p>
<input type="hidden" name="post_id" id="post_id" value="<?php echo '0';?>" />
<?php wp_nonce_field('add_attachement', 'client-file-upload'); ?>
</p>
<p>
<input type="submit" value="Save all changes" name="save" style="display: none;">
</p>
</form>