I'm trying to send jQuery data via AJAX to a WordPress template file. I've tried several different techniques and solutions based on other questions posted that pertain to this topic, with no success. I can successfully pass data from the functions.php file to my promotions.php template file.
However, I cannot get the data from my JavaScript file (ajax-javascript.js) file to the functions.php file. When the page loads, my $_POST variable is empty and my console.log message from my ajax-javascript.js file reads 'Server response from the AJAX URL 0'. To me, a response code of '0' means there is something wrong with my wp_ajax hooks but I cannot figure out what. Is there something wrong with the hooks or is it something else that I'm over-looking?
Here is my latest attempt:
ajax-javascript.js
jQuery(document).ready(function($) {
var numberOfPromos = 4;
var data = {
numberOfPromos: numberOfPromos
};
$.post('/wp-admin/admin-ajax.php', data, function(response) {
console.log('Server response from the AJAX URL ' + response);
});
});
functions.php
add_action( 'wp_enqueue_scripts', 'add_ajax_javascript_file' );
function add_ajax_javascript_file() {
wp_localize_script( 'ajax_for_frontend', 'ajax_for_frontend', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/js/ajax-javascript.js', array('jquery') );
}
add_action( 'wp_ajax_nopriv_get_number_of_promos', 'get_number_of_promos' );
add_action( 'wp_ajax_get_number_of_promos', 'get_number_of_promos' );
function get_number_of_promos() {
echo $_POST['numberOfPromos'];
die();
}
promotions.php - where I call my function in my Wordpress template file
<div><?php echo $get_number_of_promos(); ?></div>