1

I have a professional registration form, where fit by entering the name and the image (photo). This file is used in Ajax, I can do it, but it must be done in Ajax, and an image I can not send, even using formData. Here's how my code is at the moment.

page-register.php

<form id="form-professionals">
  <input type="text" id="name" name="name" required placeholder="Insert the Name" value=""/>
  <input type="file" name="image" id="image">
  <button id="button-register-professionals">Register</button>
  <div class="notification-profesionals"></div>
</form>

scripts.js

$(document).ready(function () {
$('#button-register-professionals').click(function () {
var name = $('#name').val();
var image = $('#image').val();
if (name == '') {
    alert('Required Field');
} else {
    $.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {
            action: 'register_professionals',
            name: name,
            image: image
        },
        success: function (response) {
            $('.notification-profesionals').html(response);

        },

        error: function (response) {
            console.log('error: ' + response);
        }
    });
}
return false;
});
});

functions.php

add_action('wp_ajax_nopriv_register_professionals', 'register_professionals');
add_action('wp_ajax_register_professionals', 'register_professionals');

function register_professionals(){
$post_type = 'professionals';
$title = $_POST['name'];
$image = $_FILES['image'];


$new_post = array(
'post_title' => $title,
'post_status' => 'pending',
'post_type' => $post_type,

);

wp_insert_post($new_post);

if (!function_exists('wp_generate_attachment_metadata')) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($image) {

foreach ($image as $file => $array) {
    if ($image[$file]['error'] !== UPLOAD_ERR_OK) {
        return "upload error : " . $image[$file]['error'];
    }
    $attach_id = media_handle_upload($file, $id);
}
} else {
echo 'error - image';
}
if ($attach_id > 0) {
update_post_meta($id, '_thumbnail_id', $attach_id);
echo 'success - add image';

} else {
echo 'error - add image';
}

if ($id) {
echo 'Success';
} else {
echo 'Error';
}
die();
}

0 Answers0