Call any Wordpress PHP function via AJAX

13,809

Solution 1

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> 

Solution 2

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",
  ) );
} );
Share:
13,809

Related videos on Youtube

Alex Cardo
Author by

Alex Cardo

Free Samples by MAIL

Updated on September 16, 2022

Comments

  • Alex Cardo
    Alex Cardo over 1 year

    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.

  • Alex Cardo
    Alex Cardo over 6 years
    Oh, sorry... I start to realize )))
  • Elvin Haci
    Elvin Haci over 6 years
    In the given example add_action() functions call say_hello_function; At the 1st row you see add_action('wp_ajax_nopriv_sayhello', 'say_hello_function'), right? add_action is WP Core function which executes second parameter as a function.
  • Elvin Haci
    Elvin Haci over 6 years
    It can be interpreted so: add_action('wp_ajax_nopriv_sayhello', 'say_hello_function') = Hey WP, run a function called 'say_hello_function' when you get action=sayhello GET parameter from front-end side and return its output to front-end side.
  • Alex Cardo
    Alex Cardo over 6 years
    Yes, yes, sorry. I was inattentive! You're right...
  • Alex Cardo
    Alex Cardo over 6 years
    I know that I need to write something like die() at the end. Isn't it?
  • Elvin Haci
    Elvin Haci over 6 years
    Yes, "die" or "exit". i have written exit() in my example, check it please.
  • Alex Cardo
    Alex Cardo over 6 years
    Hello, Maxwell! Thank you for this hint. I will study WP Rest API. Maybe this will work for me.
  • Maxwell s.c
    Maxwell s.c over 6 years
    If you like OO, check out the WP rest class to extend.