admin管理员组文章数量:1290093
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.
Below is the console log
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.
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.
Below is the console log
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.
Share Improve this question asked Jun 28, 2021 at 21:22 JamesJames 112 bronze badges 4 |1 Answer
Reset to default 1I 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.
本文标签: phpAJAX wpinsertuser WORKS but responds with quotThe site is not enabledquot
版权声明:本文标题:php - AJAX wp_insert_user WORKS but responds with "The site is not enabled" 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741475763a2380873.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
wp_send_json_success
, so my guess is that this is coming from the WPDB error message. It's also possible that not all paths through your classes code result in a die or exit statement, and the code outputting this message has nothing to do with this AJAX handler. Perhaps you should check the network admin and verify that the site is activated/enabled? – Tom J Nowell ♦ Commented Jun 28, 2021 at 22:19