2

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:

twentyseventeen\js\my-ajax-script.js:

$(document).ready(function() {
    $.ajax(
        {
            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

  • One of your issues is a common one - WordPress jQuery is in noConflict mode, meaning there's no $ alias to begin with. You need to do something like these answers suggest. What is you action hook code? – Howdy_McGee Aug 18 '17 at 16:29
  • Hey there, yes! that worked for resolving the jquery not found error but still not getting the array of fruits back. Now I am getting a 0 response printed to console. I appreciate the help :) Not sure what you mean by action hook code... All the code I added following a fresh WP install is posted above, everything else is default. – AnchovyLegend Aug 18 '17 at 16:38
4

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']]);
    exit();
}
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.

  • 1
    I know this is an old post, but why echo instead of return? – rudtek Oct 19 '17 at 18:00
  • @rudtek While using wp_ajax_* I don't believe you can return and have to echo but I cannot tell you why off the top of my head. This may be a good question on it's own if it hasn't already been asked on the site! – Howdy_McGee Oct 19 '17 at 18:13
0

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
wp_send_json_success(array('response'=>$response));
// by using wp_send_json_success() you don't need to exit and parse response
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.