Basic WordPress AJAX Call

I have a fresh WP install and for purposes of keeping things simple I currently just have a simple action as follows in my functions.php:

function getFruits() {
    return json_encode( ['fruits' => ['apples', 'pears']]);

function my_enqueue() {    
    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

    wp_localize_script( 'ajax-script', 'my_ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

Now, my objective is to use JQuery / JavaScript to make an AJAX call to my wordpress endpoint and get the fruits json object back and print it console simply when rendering the landing page.

This is what I tried:


$(document).ready(function() {
            type: "get",
            data : {
                action: 'getFruits'
            dataType: "json",
            url: my_ajax_object.ajax_url,
            success: function(msg){
                console.log(msg); //output fruits to console

Currently, I am getting a JQuery is not defined error, although it seems to be enqueued. Second, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.

Thank you

Solutions Collecting From Web of "Basic WordPress AJAX Call"

WordPress AJAX uses actions to connect your jQuery action with a traditional WordPress action. Take a look at the example WordPress provides in their docs. There’s 2 hooks:

add_action( "wp_ajax_{$jquery_action_string}", "callback_function_name" );

The above will only work for authenticated ( logged in ) users. For non-logged-in users we use nopriv:

add_action( "wp_ajax_nopriv_{$jquery_action_string}", "callback_function_name" );

So in our case we would use both:

function return_fruits() {
    echo json_encode( ['fruits' => ['apples', 'pears']]);
add_action( 'wp_ajax_getFruits', 'return_fruits' );
add_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' );

Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to echo this data instead of return it.

You have to use ajax action hook to perform your jquery action.

for login user:

add_action('wp_ajax_getFruits', 'getFruits);

for not login user:

add_action('wp_ajax_nopriv_getFruits', 'getFruits');

function get_fruits(){
$response = array('Fruits'=> ['banana', 'apple']);
//use this function and make a response then send the response
// by using wp_send_json_success() you don't need to exit and parse response