AJAX wp_INSERT_USER工作正常,但响应为“该站点未启用”

时间:2021-06-28 作者:James

我的网站上有一个附有AJAX事件的表单。在我调用wp\\u insert\\u user函数之前,AJAX事件似乎一直在运行,我不明白为什么,但当我在函数运行之前放置wp\\u send\\u json\\u success,但之后立即返回一些文本时,我收到了一个;站点未启用“;回答

enter image description here

下面是控制台日志

enter image description here

我缩短了代码,因为类非常大。

JavaScript代码:

const axios = require(\'axios\');

class campaign_submission_stage_one {

    constructor() {
        // stage one form
        const form = document.querySelector(\'form\');

        if(form){
            // process data on form submit
            form.addEventListener(\'submit\', (e) => {
                e.preventDefault();

                // passes data on to prepare method
                this._request();
            })
        }
    }

    _request(formData){
        console.log(formData)

        // needs to be "FormData" for axios to work
        const data = new FormData(from);

        // action is the function that is receiving this data
        data.append(\'action\', \'campaign_submission_stage_one\');

        // _wpnonce for form authentication
        data.append(\'_wpnonce\', formData.nonce);

        // campaign details
        data.append(\'campaign\', formData.campaign);
        data.append(\'job\', formData.job);

        // form input data
        data.append(\'first_name\', formData.first_name);
        data.append(\'last_name\', formData.last_name);
        data.append(\'email\', formData.email);
        data.append(\'password\', formData.password);

        // post the data
        axios.post(wp_obj.ajaxUrl, data)

        // response
        .then(response => {
            console.log(response);

            // error
            if(response.status === \'error\'){
                const errorMessageDiv = form.querySelector(\'.ajax-error\');
                errorMessageDiv.style.removeProperty(\'display\');
                errorMessageDiv.innerText = response.message;

            // success
            } else {
                window.location.reload(true);
            }
            
        })

        // error catching
        .catch((error) => {
            this._error(error)
        });
    }
}

new campaign_submission_stage_one();
PHP代码

<?php

add_action( \'wp_ajax_campaign_submission_stage_one\', \'campaign_submission_stage_one\');
add_action( \'wp_ajax_nopriv_campaign_submission_stage_one\', \'campaign_submission_stage_one\');

function campaign_submission_stage_one() {
    $create = new campaignSubmissionStageOne();

    $create->initialize();
}

class campaignSubmissionStageOne {

    public $campaign_id = 0;
    public $job_id = 0;
    public $required_form_data = array();
    public $user_id = 0;

    public function __construct(){
        // empty
    }

    public function initialize() {
        if (is_user_logged_in() === true) {
            $this->returnMessage(\'This application is for new users only.\');
        }

        // authenticate form nonce
        check_ajax_referer( "campaign_submission_stage_one_nonce", "_wpnonce");

        if(isset($_POST)) {
            $this->validateData($_POST);

        } else {
            $this->returnMessage(\'No information provided.\');
        }
    }

    public function validateData($data){
        $this->setCampaignId($_POST[\'campaign\']);
        $this->setJobId($_POST[\'job\']);

        // set required fields for below validation
        $this->setRequiredFormData($data);

        // check that all required values are present
        $required_fields = $this->getRequiredFormData();
        foreach($required_fields as $key => $value){
            if(empty($value)){
                $this->returnMessage(\'Required \' . $key . \' value missing.\');
            }
        }

        // data validation passed, now validate if they are a new user or not
        $this->existingUserCheck();
    }

    public function setCampaignId($campaign_id){
        $this->campaign_id = sanitize_text_field($campaign_id);
    }

    public function getCampaignId(): int {
        return $this->campaign_id;
    }

    public function setJobId($job_id){
        $this->job_id = sanitize_text_field($job_id);
    }

    public function getJobId(): int {
        return $this->job_id;
    }

    public function setRequiredFormData($data){
        $this->required_form_data = [
            \'first_name\' => trim(sanitize_text_field( $data[\'first_name\'] )),
            \'last_name\' => trim(sanitize_text_field( $data[\'last_name\'] )),
            \'password\' => trim(sanitize_text_field( $data[\'password\'] )),
            \'email\' => trim(sanitize_email( $data[\'email\'] )),
        ];
    }

    public function getRequiredFormData(): array {
        return $this->required_form_data;
    }

    /**
     * Checks if a user exists with submitted email address, if so reject otherwise create user.
     */
    public function existingUserCheck(){
        $existing_user = email_exists($this->getRequiredFormData()[\'email\']);

        if($existing_user){
            $this->returnMessage(\'A user already exists with this email address.\');
        } else {
            $this->createNewUser();
        }
    }

    public function createNewUser(){
        $full_name = $this->getRequiredFormData()[\'first_name\'] . \' \' . $this->getRequiredFormData()[\'last_name\'];

        $user_data = [
            \'user_login\' => $this->getRequiredFormData()[\'email\'],
            \'user_pass\' => $this->getRequiredFormData()[\'password\'],
            \'user_email\' => $this->getRequiredFormData()[\'email\'],
            \'first_name\'=> $this->getRequiredFormData()[\'first_name\'],
            \'last_name\'=> $this->getRequiredFormData()[\'last_name\'],
            \'nickname\' => $full_name,
            \'role\' => \'applicant\'
        ];


        // if successful returns a user id, otherwise returns an error
        $user_id = wp_insert_user( $user_data );


        if( is_wp_error( $user_id) ) {
            $error_string = $user_id->get_error_message();

            $this->returnMessage($error_string);

        } else {
            $this->setUserId($user_id);
            $this->appendAdditionalUserMeta();
        }
    }

    public function setUserId($user_id){
        $this->user_id = $user_id;
    }

    public function getUserId(): int {
        return $this->user_id;
    }

    public function appendAdditionalUserMeta(){
        $user_id = $this->getUserId();

        update_user_meta( $user_id, \'show_admin_bar_front\', \'false\' );

        // insert record into job applications table
        $this->insertIntoJobApplicationsTable();
    }

    public function insertIntoJobApplicationsTable(){
        if( !isset($wpdb) ) {
            global $wpdb;
        }

        $result = $wpdb->insert(
            $wpdb->prefix . \'job_applications\',
            array(
                \'job_id\' => $this->getJobId(),
                \'campaign_id\' => $this->getCampaignId(),
                \'applicant_id\' => $this->getUserId(),
                \'applied_time\' => current_time(\'mysql\', 1)
            ),
            array(
                \'%d\',
                \'%d\',
                \'%d\',
                \'%s\'
            )
        );

        // false means insert failed
        if($result === false){
            $this->returnMessage($wpdb->print_error());
        } else {
            // insert was successful so notify user
            $this->registrationComplete();
        }
    }
    
    public function registrationComplete(){
        $user_email = $this->getRequiredFormData()[\'email\'];
        $user_password = $this->getRequiredFormData()[\'password\'];

        // Log user in so we have an applicant id for the next stage of the application
        wp_signon( array( \'user_login\' => $user_email, \'user_password\' => $user_password ) );

        $this->returnAction();
    }

    public function returnMessage($message){
        wp_send_json_success(array(\'status\' => \'error\', \'message\' => $message));
    }

    public function returnAction(){
        wp_send_json_success(array(\'status\' => \'success\', \'action\' => \'reload\' ));
        wp_die();
    }
}

新用户在WP Admin中显示时正在创建,但数据库中没有显示insertIntoJobApplicationsTable()数据,因此怀疑WP\\u insert\\u用户有问题。

我有PHP错误日志,我没有看到任何错误出现。

我已经被困在这几个小时了。。。因此,如果有人能提供帮助或提示,我将非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:James 整理而成

我决定关闭每个插件,结果发现有一些代码将user\\u register操作注册到插件事件中,该事件在创建用户时触发,由于该代码需要特定数据,因此失败。

我禁用了此操作,我的代码现在正在运行。

相关推荐

有没有办法让客户在不调用wp-login.php的情况下注销?

我正在使用woo commerce。注销URL不同,其中包括“customer logout”。实际上,它再次重定向到“wp登录”。php’使注销过程成功。我的问题是,当Woo commerce不调用“wp登录”时。php’用于登录,为什么它需要注销?我知道,至少5年来,这一问题已经被问了好几次,但没有直接的答案。我正在管理区使用htaccess密码锁。使用此功能,任何新/现有客户都可以注册和登录,而不会出现任何问题。但是,当客户注销时,由于wp登录。php被调用,它要求htaccess用户名和密码。这意