How to get update ACF fields from AJAX form data

Viewed 1198

I can send the data to admin-ajax.php and see that the data exists via my dev tools, however, I cannot seem to be able to take that data and update an ACF field, or perhaps my function to do that is not running.

Here is my PHP:

// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action( 'wp_ajax_add_dog_to_favorites', 'add_dog_to_favorites' );
add_action( 'wp_ajax_nopriv_add_dog_to_favorites', 'login_to_add_to_favorites' );

// define the function to be fired for logged in users
function add_dog_to_favorites() {


    // nonce check for an extra layer of security, the function will exit if it fails
    if (!wp_verify_nonce( $_REQUEST['nonce'], 'add_dog_to_favorites_nonce' )) {
        exit('Woof Woof Woof');
    } 
    
    // Get the post_id and user_id value from the form and update the ACF form "test_field".
    $post_id = $_REQUEST["post_id"];
    $userID = $_REQUEST('user_id');
    $current_field = get_field('test_field', $userID);
    update_field('test_field', $post_id, $userID);

    if ($current_field === false) {
        $result['type'] = 'error';
    } else {
        $result['type'] = 'success';
    }



    // Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $result = json_encode($result);
        echo $result;
    } else {
        header("Location: " . $_SERVER['HTTP_REFERER']);
    }

    // don't forget to end your scripts with a die() function - very important
    die();

}

// define the function to be fired for logged out users
function login_to_add_to_favorites() {
    echo 'You must log in to like';
    die();
}

// used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.

// Fires after WordPress has finished loading, but before any headers are sent.

add_action( 'init', 'enqueue_add_dog_to_favorites_script' );

function enqueue_add_dog_to_favorites_script() {
    // Register the JS file with a unique handle, file location, and an array of dependencies
    wp_register_script( 'add_favorites_script', plugin_dir_url( __FILE__ ) . 'add_favorites_script.js', array('jquery') );

    // localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
    wp_localize_script( 'add_favorites_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

    // enqueue jQuery library and the script you registered above
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'add_favorites_script' );
}

and my JS:

jQuery(document).ready( function() {
    jQuery(".not-favorite").click( function(e) {
       e.preventDefault(); 
       post_id = jQuery(this).attr("data-post_id");
       nonce = jQuery(this).attr("data-nonce");
       user_id = jQuery(this).attr("data-user_id");
       jQuery.ajax({
          type : "post",
          dataType : "json",
          url : myAjax.ajaxurl,
          data : {action: "add_dog_to_favorites", post_id : post_id, nonce: nonce, user_id : user_id},
          success: function(response) {
            if(response.type == "success") {
               console.log('success!');
            }
            else {
               alert("Your like could not be added");
            }
         }
      });
    });
 });

I have a console.log('success!'); line that should trigger if successful, but it is not triggering. The failure alert is also not triggering, which leads me to believe the function is not running at all? I feel like it's pretty close to working, but just can't get there.

Any help would be greatly appreciated!


Update: Ok. I found that the function is actually exiting because of the nonce verification:

    if (!wp_verify_nonce( $_REQUEST['nonce'], 'add_dog_to_favorites_nonce' )) {
        exit('Woof Woof Woof');
    }

I have tried commenting this block of code out to see what would happen and I get a critical error.


Update: Fixed an error in my code that allows it to work without the nonce check.

$userID = $_REQUEST('user_id'); needs to be $userID = $_REQUEST['user_id'];

I still will need to get the nonce check working, but progress is being made. If anyone knows why that is not working, that would wrap this up!

0 Answers
Related