WordPress front end AJAX returns 0

So I've come to the conclusion that WP AJAX is a mess. That being said I'm not seeing where I made my error here.

For the record I get zero no matter what, whether I use the security nonce or not, whether I change the function names I always get zero. Even if I change the function names not to match I get no actual error, just 0.

I've done a search here and most of the relevant topics refer to a typo or not matching up the function names.

For the record this is a Front end function. Thanks!

PHP in functions.php

function mcc_scripts() {
  wp_register_script( 'safety-campaign', get_template_directory_uri() . '/js/safety-campaign.js', array('jquery'), '0.0.1', true );
  wp_localize_script( 'safety-campaign', 'MyAjax', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'security' => wp_create_nonce( 'some_string' )
add_action( 'wp_enqueue_scripts', 'mcc_scripts' );

// The function that handles the AJAX request
function save_pledge() {
  check_ajax_referer( 'some_string', 'security' );
  echo 'test'; //Checking in the XHR network tab this also responds 0 
  //The request does show the proper data being passed though

add_action( 'wp_ajax_nopriv_save_pledge', 'save_pledge' );

Javascript that calls this function

    var data = {
      action: 'save_pledge',
      security : MyAjax.security,
      formdata : $("#campaign-form").serialize()

    $.post(MyAjax.ajaxurl, data, function(response) {
      console.log(response) // This responds 0

1 answer

  • answered 2018-03-13 20:41 Rick Calder


    For those struggling with this same thing, apparently WP AJAX requires BOTH hooks. The solution was also adding the one without nopriv

    add_action( 'wp_ajax_save_pledge', 'save_pledge' ); //This is required TOO
    add_action( 'wp_ajax_nopriv_save_pledge', 'save_pledge' );