It's very difficult for me to learn the basics of AJAX since I was managed to find only complicated examples. In fact, I want to do an apparently simple thing, but I wasn't able to find any easy solution. There are numerous instructions how to use AJAX to check various forms, etc. But there is few data how this technology work in WordPress.
The official instruction was useless to me as well: https://codex.wordpress.org/AJAX_in_Plugins
What exactly I need?
For example, I have some function in functions.php. Let it be a just simple string:
<?php
function do_echo() {
echo "Hello";
}
Now, I want to create a button inside my post and call do_echo() using AJAX.
<button class="my_button" type="button" role="button">Click Me</button>
So, the first and foremost thing I want to do is just push on the button and get "Hello, world!" displayed.
Of course, in fact, I need to execute the more complicated function. But, first of all, I need to do these simple things.
I realize that I need to do something like this using jQuery
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script,
or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
I understand that I need to do something like this in PHP
add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback');
But I can't understand what exact steps I need to do to attach these things to WordPress.
Can anyone assist me with the simple instruction how to call any PHP function from functions.php in WordPress using AJAX when the button was clicked?
Thank you in advance.