I'm trying to do a custom AJAX action on WordPress but it isn't working. I have the following form:
<form method='post' name='form-bid-<?php echo get_the_ID() ?>' class="bid-form">
<input type='submit' name='<?php echo get_the_ID()?>' value='Licitar' class='bidvalue'>
<?php wp_nonce_field('ajax-bid-nonce', $post->ID); ?>
</form>
The form is this way because it's generated inside a loop, one for every post on the site, therefore I use the post ID as the unique name for the input.
Then, I capture the form submit on a custom JavaScript file:
jQuery(document).ready(function($) {
// Perform AJAX bid on form submit
$('form.bid-form').on('submit', function(e) {
var action = 'ajaxbid';
var auction_id = e.target.name.substring('form-bid-'.length);
var security_container = "#".concat(auction_id);
var security = $(security_container).val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_bid_object.ajaxurl,
data: {
'action': action,
'id': auction_id,
'security': security
},
success: function(data) {
console.log(data);
}
});
e.preventDefault();
});
});
This part works, and it prints 0 on the console upon success.
Finally, I have a PHP file where I register the script and have the function I want to call upon the form submission:
function ajax_bid_init() {
wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );
wp_enqueue_script('ajax-bid-script');
wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// Enable the user with no privileges to run ajax_bid() in AJAX
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
}
add_action('init', 'ajax_bid_init');
function ajax_bid() {
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-bid-nonce', 'security');
echo json_encode(array('message'=>__('SUCCESS')));
die();
}
For now, all I wanted was the function to return that array and display it on console. However, the code never seems to run through here, and the AJAX response is always 0.
I have done a quite similar approach to both login and registration on the website and they both work. I've compared the 3 endless times and I cannot seem to find what I'm missing here.