AJAX wp_insert_user WORKS but responds with “The site is not enabled”

I have a form on my site which has an AJAX event attached. The AJAX event seems to be working up until I call the wp_insert_user function, I don’t understand why but when I put a wp_send_json_success before the function it works, but straight after, even just returning some text I receieve a “The site is not enabled” response.

AJAX wp_insert_user WORKS but responds with “The site is not enabled”

Below is the console log

AJAX wp_insert_user WORKS but responds with “The site is not enabled”

I’ve shortened the code as the classes are quite large.

JavaScript code:

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 code

<?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();
    }
}

The new user is being created as they appear in the WP Admin, but the insertIntoJobApplicationsTable() data is not appearing in the DB so suspect there is something going wrong with wp_insert_user.

I have PHP error loggin on and I am not seeing any errors appearing.

I’ve been stuck on this for hours… so if anyone could help or give some tips I would greatly appreciate your help.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I decided to turn off every plugin and it turns out there was some code that had a user_register action registered to a plugin event which fired whenever a user was created, and as this code required specific data it was failing.

I disabled this action and my code is now working.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x