Wordpress Widget: AJAX Request fails

Viewed 29

I'm trying to make an AJAX-Request within a Wordpress Plugin in frontend, after clicking a button. -> Actually it is a Widget. So I implemented the frontend via extending de WP_Widget Class. I don't know if this is worth knowing.

I always get a 400 bad Request and '0'. I dont wanted to use JQuery, but i also tried and there I get a 500 Internal Server Error. Now im really confused.

I really searched up and down the internet and every question in this forum (I know there are many similar questions - but nothing worked to me)

I'm so thankful if anyone can help me.

Main Plugin File:

function scriptloader(){

$scripturl = plugin_dir_url(__FILE__) . 'includes/public/script.js';
wp_enqueue_script('script-js', $scripturl, array( 'jquery' ));

$styleurl = plugin_dir_url(__FILE__) . 'includes/public/css/main.css';
wp_enqueue_style('script-js', $styleurl, [], null, false);

$js_variable = [
    'ajax_url' => admin_url('admin-ajax.php'),
    'ajax_nonce' => wp_create_nonce( 'ajax_public' ),
    'mystring' => "LOL!"
];
wp_localize_script('script-js', 'phpwindowobject', $js_variable);
};
add_action( 'wp_enqueue_scripts', 'scriptloader');


function k_ajax_requester(){

$mystring = "SERVER ALIVE";
echo $mystring;
wp_die();

};

add_action('wp_ajax_k_ajax', 'k_ajax_requester');
add_action('wp_ajax_nopriv_k_ajax', 'k_ajax_requester');

There is a button in frontend.php which executes ajaxrequest() by clicking in my script.js :

function ajaxrequest(){
    
var url = phpwindowobject.ajax_url;

var data = {action: "k_ajax",mystring: "K_AJAX"}

console.log("Data to send:")
console.log(data)

var xhrobj = new XMLHttpRequest;
xhrobj.open('POST', url, true);
xhrobj.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
xhrobj.onreadystatechange = function()
{
    if (this.readyState == 4)
    {
        if (this.status == 200)
        {
            if (this.responseText != null)
            {
                console.log('Request completed');
            }
            else console.log("Ajax error: No data received")
        }
        else console.log("Ajax error: " + xhrobj.statusText );
    }
};
xhrobj.onload = function(){
    var answer = (xhrobj.response);
    console.log(answer);
}
xhrobj.send(data);

};

What do you think?

Thank you.

0 Answers
Related