0

I have a form for adding a post via AJAX and PHP. I have three fields. Text, textarea and file input field.

Everything it's working, but it won't upload a featured image. When I remove the AJAX call, then it's working. It only uploads the text and the textarea field.

Here is the form:

public function pp_html_template() {

    if ( is_user_logged_in() ) {
        return '<h2>' . __( 'Publish your post', 'post-publisher' ) . '</h2>
        <form id="pp-form-submit" name="pp-form-submit" class="pp-form-submit" enctype="multipart/form-data">' .
       wp_nonce_field( 'pp_publisher_save', 'pp_publisher_name' )
       . '<div class="pp-row">
                <label for="pp_title">' . esc_attr__( 'Title', 'post-publisher' ) . '</label>
                <input type="text" id="pp_title" name="pp_title">
            </div>

            <div class="pp-row">
                <label for="pp_content">' . esc_attr__( 'Content', 'post-publisher' ) . '</label>
                <textarea name="pp_content" id="pp_content" name="pp_content" cols="30" rows="10"></textarea>
            </div>
            
            <div class="pp-row">
                <label for="pp_featured_image">' . esc_attr__( 'Featured Image', 'post-publisher' ) . '</label>
                <input type="file" id="pp_featured_image" name="pp_featured_image">
            </div>
            <input type="hidden" name="action" value="pp_html_process"/>
            <div class="pp-row">
                <input type="submit" name="pp_submit" id="pp_submit">
            </div>
        </form>';
    }
}

Here is the form process:

public function pp_html_process() {

    // Process the form
    if ( isset( $_POST['pp_submit'] ) ) {
        if ( ! isset( $_POST['pp_publisher_name'] ) || ! wp_verify_nonce( $_POST['pp_publisher_name'], 'pp_publisher_save' ) ) {
            esc_attr__( 'Sorry, this action is not allowed.', 'post-publisher' );
            exit;
        } else {
            global $current_user;

            $user_login   = $current_user->user_login;
            $user_id      = $current_user->ID;
            $post_title   = sanitize_text_field( $_POST['pp_title'] );
            $post_content = sanitize_textarea_field( $_POST['pp_content'] );

            $new_post = array(
                'post_title'   => $post_title,
                'post_content' => $post_content,
                'post_type'    => 'post',
                'post_status'  => 'draft',
                'post_name'    => str_replace( ' ', '-', $post_title ),
            );

            $post_id = wp_insert_post( $new_post, true );

            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' );
            }


            $featured_image = media_handle_upload( 'pp_featured_image', $post_id );
            if ( $featured_image > 0 ) {
                update_post_meta( $post_id, '_thumbnail_id', $featured_image );
            }

            if ( wp_doing_ajax() ) {
                echo 'Post created! ID';
                wp_die();
            }
        }
    }
}

Here is the __contstruct()

public function __construct() {
    if ( ! is_admin() ) {
        add_shortcode( 'pp_html_template', array( $this, 'pp_html_template' ) );
        add_action( 'template_redirect', array( $this, 'pp_html_process' ) );
    }
    add_action( 'wp_ajax_pp_html_process', array( $this, 'pp_html_process' ) );
    add_action( 'wp_ajax_nopriv_pp_html_process', array( $this, 'pp_html_process' ) );

}

And here is the AJAX:

jQuery(document).ready(function ($) {
    function ajaxSubmit() {
        var formData = new FormData(this);

        formData.append('pp_submit', 1);

        $.ajax({
            action: 'pp_featured_image',
            type: 'POST',
            url: public_ajax.ajaxurl,
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                console.log('success', response);
            },
            error: function (response) {
                console.log('error!', response);
            }
        });

        return false;
    }

    $('#pp-form-submit').submit(ajaxSubmit);
});

I'm not getting any errors in the console. Any help would be appreciated.

7
  • Try if ( is_wp_error( $featured_image ) ) { wp_die( $featured_image ); } right after you called media_handle_upload(). If there was an error, then the dump output would show it. (Just check the console to see the dump output)
    – Sally CJ
    Sep 22 at 16:25
  • @SallyCJ There are no errors. It is just loading: prnt.sc/1t8wkqs The featured image is working just fine without AJAX.
    – upss1988
    Sep 22 at 16:35
  • Sorry about that "dump output" - I forgot to edit that part in my comment. Anyway, try uploading a new PNG/JPEG image, via your form, and see if the image is in the Media → Library? Also, try enabling WP_DEBUG and WP_DEBUG_LOG.
    – Sally CJ
    Sep 22 at 17:01
  • You can also try using fetch() instead - replace the whole jQuery.ajax() call with fetch( public_ajax.ajaxurl, { method: 'POST', body: formData } ).then( res => res.text() ).then( data => console.log( 'fetch success', data ) ); However, judging from that screenshot, the server may have failed to generate the thumbnail's metadata (which includes sub-sizes/resized images) or maybe a plugin/code caused the issue. So try deactivating all plugins and see if the same issue persists.
    – Sally CJ
    Sep 22 at 17:54
  • Hey @SallyCJ, thanks for your help, but the issue was up to the folder permission. Now everything works.
    – upss1988
    Sep 23 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.