I'm trying to create the hooks and function for the php to receive my ajax call and when the response is alerted, all I receive is 0.
I suppose my question is, are the add_action hooks supposed to go into the bottom of the admin-ajax.php file or are they supposed to go elsewhere? Keep in mind that my Ajax request is on a custom template .php file.
Here's the code for reference:
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback(){
echo "Baffles";
$first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';
$last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';
?>
<p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p>
<?php
die(); // required. to end AJAX request.
}
Jquery/Ajax Request
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
url: '../wp-admin/admin-ajax.php',
data: {
action : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook
first_name : 'John', // PHP: $_POST['first_name']
last_name : 'Cena', // PHP: $_POST['last_name']
}, success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
wp_ajax_{$_REQUEST[‘action’]}
hook. developer.wordpress.org/reference/hooks/wp_ajax__requestaction This tutorial is quite useful: rudrastyh.com/wordpress/load-more-posts-ajax.html