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