• mabufoysal

    (@mabufoysal)


    I am working on a Custom Plugin. I have below JavaScript code.

    const sent_urls = () => {
            const formData = new FormData();
            formData.append('action', 'start_parsing');
            formData.append('of_start_parsing_nonce', of_start_parsing_nonce.value);
            formData.append('urls', urls.slice(offset, offset + limit));
    
            formData.append( 'category_fans', category_fans );  //This is added by me
    
            fetch(ajaxurl, {
                method: 'POST',
                body: formData
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            }).then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
    
                if (!data.result) {
                    throw new Error('Unknown error');
                }
    
                added += data.result.added;
                exists += data.result.exists;
                error_urls = error_urls.concat(data.result.error);
                offset += limit;
                count_urls.textContent = 'Imported ' + all_urls + ' urls. ' + 'Added ' + added + ' urls. Exists ' + exists + ' urls. ' + 'Error ' + error_urls.length + ' urls.';
    
                if (offset >= urls.length) {
                    enable();
    
                    alert.show_success('Parsing complete. Added ' + added + ' urls. Exists ' + exists + ' urls.');
    
                    if (error_urls.length > 0) {
                        textarea.value = error_urls.join('\n');
                    } else {
                        textarea.value = '';
                    }
    
                    offset = 0;
                    added = 0;
                    exists = 0;
                    error_urls = [];
    
                    return;
                } else {
                    sent_urls();
                }
            }).catch(error => {
                enable();
                alert.show_warn(error);
            });
        }

    My AdminAjax class is like below.

    <?php
    
    
    namespace OnlyFansPlugin;
    
    use PhpOffice\PhpSpreadsheet\IOFactory;
    
    use function get_class_methods;
    
    
    class AdminAjax {
        /**
         * The function is a constructor that registers actions.
         */
        public function __construct() {
            $this->register_actions();
        }
    
        /**
         * The function "start_parsing" starts parsing.
         */
        public function start_parsing() {
    
            if ( ! $this->verify( 'start_parsing' ) ) {
                echo wp_json_encode(
                    array(
                        'error' => 'Error request.',
                    )
                );
                wp_die();
            }
    
    
    
            $category = $this->get_post_field( 'category_fans', '' );
    
            error_log(print_r($category));
    
    
    
            $urls_str = $this->get_post_field( 'urls', '' );
    
            $urls = explode( ',', $urls_str );
    
    
    
    
            if ( ! $urls ) {
                echo wp_json_encode(
                    array(
                        'error' => 'Error: wrong list urls.',
                    )
                );
                wp_die();
            }
    
            $added  = 0;
            $error  = array();
            $exists = 0;
    
            foreach ( $urls as $raw_url ) {
                $url = trim( $raw_url );
    
                if ( '' === $url || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
                    continue;
                }
    
                $parser  = new Parser( $url );
                $account = $parser->get_account();
    
                if (!$account->is_valid()) {
                    $error[] = 'Error on parse: ' . $url;
                    continue;
                }
    
                // if account not exists.
                if ( $account->get_post_id() === 0 ) {
                    $success = $account->save();
    
                    if ( $success ) {
                        $added += 1;
                    } else {
                        $error[] = 'Error on save: ' . $url;
                    }
                } else {
                    // if account exists then delete images.
                    $account->delete_images();
                    $exists += 1;
                }
            }
    
            $response = array(
                'result' => array(
                    'added'  => $added,
                    'error'  => $error,
                    'exists' => $exists,
                ),
            );
    
            echo wp_json_encode( $response );
            wp_die();
        }
    
        /**
         * The function "get_nonce_field" generates a nonce field for a form.
         *
         * @param string $action_name The "action_name" parameter is a string that represents the name of the action
         * or form being verified. It is used to generate the nonce and action names for the form.
         *
         * @return void
         */
        public static function get_nonce_field( string $action_name ) {
            wp_nonce_field( "of_{$action_name}_action", "of_{$action_name}_nonce" );
        }
    
        /**
         * The function "register_actions" registers actions.
         *
         * @return void
         */
        private function register_actions() {
            $methods = get_class_methods( $this );
    
            foreach ( $methods as $method ) {
                if ( '_' === substr( $method, 0, 1 ) ) {
                    continue;
                }
    
                if ( 'register_actions' === $method ) {
                    continue;
                }
    
                add_action( 'wp_ajax_' . $method, array( $this, $method ) );
                add_action( 'wp_ajax_nopriv_' . $method, array( $this, $method ) );
            }
        }
    
        /**
         * The function "verify" verifies the nonce for a form.
         *
         * @param string $action_name The "action_name" parameter is a string that represents the name of the action
         * or form being verified. It is used to generate the nonce and action names for the form.
         *
         * @return bool true if the nonce is verified, false if it is not verified.
         */
        private function verify( string $action_name ): bool {
            $nonce  = "of_{$action_name}_nonce";
            $action = "of_{$action_name}_action";
    
            return isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], $action );
        }
    
        /**
         * The function "get_post_field" returns the value of the $_POST field.
         *
         * @param string $key The "key" parameter is a string that represents the name of the $_POST field.
         * @param mixed $default The "default" parameter is the default value if the $_POST field is not set.
         *
         * @return mixed
         */
        private function get_post_field( string $key, $default = '' ) {
            return isset( $_POST[ $key ] ) ? wp_unslash( $_POST[ $key ] ) : $default;
        }
    }

    I would like to catch Category like this error_log(print_r($category));

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    You need code to throw an exception when $category has an invalid value. You can then try and catch when that happens.
    https://www.w3schools.com/php/php_exception.asp

    Thread Starter mabufoysal

    (@mabufoysal)

    Thanks @brickwork . But how can I catch $category in Server Side ?

    Could you please help me in this regard ?

    Thanks.

    Moderator bcworkz

    (@bcworkz)

    PHP is a server side script. Your function needs to detect an issue and throw an exception. If you try your function and an exception is thrown, it can be caught in a catch() block. Refer to the example I linked to in my last reply.

    You’re not really catching $category itself, rather a thrown exception related to an issue with $category. If you need $category itself in your exception handler you should extend the Exception class to accept an added parameter.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Catch Form value at AJAX Form submit’ is closed to new replies.