I am struggling to get my ajax request to work. It fails when I fire my $ajax
and I get this error…
Uncaught ReferenceError: feature_ajax is not defined
This is my functions.php
// load our frontend modifiers
require_once(__DIR__ . '/lib/Frontend.lib.php');
This is my Frontend.lib.php
class php…
class Frontend
{
/** frontend constructor */
public function __construct()
{
// enqueue our scripts
add_action('wp_enqueue_scripts', array($this, 'action_wp_enqueue_scripts'));
// add out ajax actions
$this->ajax_actions();
}
/** frontend enqueued scripts */
public function action_wp_enqueue_scripts()
{
// localize admin ajax
wp_localize_script('ajax-actions', 'ajax_actions', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// enqueue scripts
wp_enqueue_script('ajax-actions');
}
/** ajax actions */
public function ajax_actions()
{
// admin field postdata ajax actions
add_action('wp_ajax_field_postdata', [__CLASS__, 'field_postdata']);
// public field postdata ajax actions
add_action('wp_ajax_nopriv_field_postdata', [__CLASS__, 'field_postdata']);
}
// Field Post Data
public static function field_postdata()
{
global $post;
$post_id = ($_REQUEST['id']);
if($post_id){
$post = get_post($post_id);
setup_postdata($post);
get_template_part('ajax/modal','field');
die();
}
}
}
new Frontend();
When I fire the $ajax
script below, this is when I get the error feature_ajax is not defined.
But it is defined in the code above.
This script below is my theme-min.js
file
// load feature post data
$.ajax({
cache: false,
timeout: 8000,
url: ajax_actions.ajaxurl,
type: 'POST',
data: {
action: 'field_postdata',
id: post_id
},
success: function (data) {
alert(data);
}
});
Any help in understanding what i’m doing wrong would be great.
Thanks
Updated Fixed Code
So what I changed to make this work. I was already enqueuing my main-min.js
file, so I combined my wp_localize_script
using the same handle as my enqueued javascript and it worked.
// register js in footer
$filename = get_template_directory_uri() . '/assets/scripts/main-min.js';
wp_register_script('main-js', $filename, array(), rand(), true);
// localize theme-js ajax actions
wp_localize_script('main-js', 'ajax_actions', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// enqueue required scripts
wp_enqueue_script('main-js')