Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call any Wordpress PHP function via AJAX [duplicate]

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.

like image 539
Alex Cardo Avatar asked Oct 20 '25 15:10

Alex Cardo


2 Answers

Okay, let's write simplified example for this.

Here is a sample for functions.php:

add_action('wp_ajax_nopriv_sayhello', 'say_hello_function');
add_action('wp_ajax_sayhello', 'say_hello_function');
function say_hello_function(){
echo 'hello';
exit();
}

And this is front-end part:

<button class="my_button" type="button" role="button">Click Me</button>

<script>
jQuery(".my_button").click(function(){

jQuery.get(ajaxurl,{'action': 'sayhello'}, 
function (msg) { alert(msg);});

});

</script>

UPD:

To display returned data in your website content:

   <script>
    jQuery(".my_button").click(function(){  
    jQuery.get(ajaxurl,{'action': 'sayhello'}, 
    function (msg) { jQuery(".result_area").html(msg);});
    });
   </script>

To get above code working you need to have a div with "result_area" class.

<div class="result_area"></div> 
like image 62
Elvin Haci Avatar answered Oct 23 '25 03:10

Elvin Haci


The best pratice is using WP Rest API

Wordpress provide an simple and organized way to add API Routes that return JSON.

You can register your routes in function.php or another loaded file.

Major WP files will be loaded and you can use your functions.

WP example:

<?php
/**
 * Grab latest post title by an author!
 */
function my_awesome_func( $data ) {
  $posts = get_posts( array(
    "author" => $data["id"],
  ) );

  if ( empty( $posts ) ) {
    return null;
  }

  return $posts[0]->post_title;
}

add_action( "rest_api_init", function () {
  register_rest_route( "myplugin/v1", "/author/(?P<id>\d+)", array(
    "methods" => "GET",
    "callback" => "my_awesome_func",
  ) );
} );
like image 44
Maxwell s.c Avatar answered Oct 23 '25 05:10

Maxwell s.c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!