How to use wp_send_json() and output the value with ajax?

Hello Wordpress Developers.

I create my own plugins, and I'm stuck about how to call php functions inside class, into javascript ajax functions.

For example we have button with ID name clickme:

button id=clickMeClick Me/button

And then I make a class with functions, example like this:

?php
class myFunctions{
function a(){
$test = Hello World from wp_send_json();
wp_send_json($test);
}

}
?

and then I want to output the test variable, using ajax. Example like this:

import $ from jquery;

class trigger{
constructor(){

this.button = $(#clickme);
this.events();

}
events(){
  this.button.on(click, this.buttonHandler.bind(this));

}

buttonHandler(){

$.ajax({
//how to call the Hello World from wp_send_json()?

success: response = {
//if success, alert the Hello World from wp_send_json;
alert();

}

});


}


}

I'm stuck, and I hope I get the help to solve it. Thank you in advance, wordpress Developers!

Topic ajax php plugin-development Wordpress javascript

Category Web


You can follow below steps:

HTMl Code:

<button id="clickMe">Click Me</button>

PHP Code: here you need to use wp_ajax hook.

class myFunctions{

    public function __construct(){
        add_action( 'wp_ajax_clickme', [$this, 'ajax_callback']); // for logged in user only
        add_action( 'wp_ajax_nopriv_clickme', [$this, 'ajax_callback']); // for non logged user only
    }

    public function ajax_callback() {
        $test = "Hello World from wp_send_json()";
        wp_send_json($test);
    }
}

$run = new myFunctions();

JS Code: for your example, you can ignore nonce, name

import $ from "jquery";

class trigger {
    constructor() {
        this.button = $("#clickme");
        this.events();
    }

    events() {
        this.button.on("click", this.buttonHandler.bind(this));
    }

    buttonHandler() {
        let ajax_url = "http://yoursite.com/wp-admin/admin-ajax.php";
        $.ajax({
            type: "post", // request type get, post
            url: ajax_url, // this sould be http://yoursite.com/wp-admin/admin-ajax.php url
            data: {
                action: "clickme", // wp_ajax_$action or wp_ajax_nopriv_$action - Important
                nonce: my_ajax_object.nonce, // must pass wp nonce and verify to protect CSRF - Very Important for Security
                name: "Razon", // your data, you can pass your own data like this - Optional
            },
            success: function(response) {
                console.log(response);
            }
        });
    }
}

Hope that help :)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.