Reputation: 31
I am developing a word press plugin for my practice, and in it i am registering a customer by taking some information.
is_user_logged_in() returns false and then i want to enque script
function theme_enqueue_scripts() {
if ( ! is_user_logged_in()){
wp_enqueue_script( 'frontend-ajax', admin_url( 'admin-ajax.php' ));
wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',admin_url( 'admin-ajax.php' ));
}
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
add_action( 'wp_ajax_PHPSidefunction', 'PHPSidefunction' );
add_action( 'wp_ajax_nopriv_PHPSidefunctionNopriv', 'PHPSidefunctionNopriv' );
and actions from ajax-call code below
$('#submitbutton').click(function() {
var $inputemail=document.getElementById('inputemail').value;
var $inputname=document.getElementById('inputname').value;
var $inputlastname=document.getElementById('inputlastname').value;
var $inputpassword=document.getElementById('inputpassword').value;
console.log($inputemail+$inputname+$inputlastname+$inputpassword);
console.log("<?php echo get_home_url(); ?>/wp-admin/admin-ajax.php");
$.ajax({
url:frontend_ajax_object,
type: "POST",
dataType: "Text",
data: {
action: "PHPSidefunctionNopriv",
inputemail: $inputemail,
inputname:$inputname,
inputlastname:$inputlastname,
inputpassword:$inputpassword
},
success: function (response) {
console.log(response);
}
error: function(errortype,textStatus,errorThrown){
console.log(errortype);
console.log(textStatus);
console.log(errorThrown);
}
});
});
and the callback function is here
function PHPSidefunctionNopriv(){
//echo 'i am phpside function nopriv';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if($_POST['action'] == 'PHPSidefunction'){
$email= $_POST['inputemail'];
$password=$_POST['inputpassword'];
$userid=wc_create_new_customer($email,$email,$password);
echo $userid;
wp_die();
}
}
}
but I'm getting the error while enqueuing script
Waiting for the help, thanks in advance.
Upvotes: 0
Views: 1483
Reputation: 177
You are trying to load PHP script as javascript file. which is totally wrong.
function theme_enqueue_scripts() {
wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',admin_url( 'admin-ajax.php' ));
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
add_action( 'wp_ajax_PHPSidefunction', 'PHPSidefunction' );
add_action( 'wp_ajax_nopriv_PHPSidefunctionNopriv', 'PHPSidefunctionNopriv' );
User is logged in or not, it doesn't matter. Ajax url will be always admin_url('admin-ajax.php')
for WP_AJAX.
Upvotes: 2