I'm trying to update a custom field in Wordpress using Ajax (e.g having a form text input replace the custom field text by the click of a button). I’m using the Advanced Custom Fields plugin and following the example I found here but this doesn't seem to work: https://support.advancedcustomfields.com/forums/topic/use-update_field-with-ajax/
What I have done is:
(1) Add html form to my single-(post-type).php
<form id="test-form" action="">
<input type="text" name="input-test" value="<?php the_field('field-name'); ?>">
<input type="submit" value="Update">
</form>
(2) update_field function in functions.php (this is an ACF function)
function test_function() {
$input_test = $_POST['input-test'];
if (!isset($input_test) || $input_test == "") { $input_test = "Fall Back"; }
update_field('field-name', $input_test);
wp_die();
}
add_action( 'wp_ajax_nopriv_test_function', 'test_function' );
add_action( 'wp_ajax_test_function','test_function' );
(3) Enqueue Js script in functions.php
function theme_scripts() {
wp_enqueue_script( 'functionality', get_template_directory_uri() . '/js/functionality.js', array ( 'jquery' ), 1.1, true);
wp_localize_script('functionality', 'MyAjax',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'postCommentNonce' => wp_create_nonce('myajax-post-comment-nonce')
)
);
}
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
(3) Create Javascript file js/functionality.js
jQuery(document).ready(function() {
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var form = "#test-form";
jQuery(form).submit(function(event) {
event.preventDefault();
jQuery.ajax({
url: ajaxurl + "?action=test_function",
type: 'post',
data: jQuery(form).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
});
Not sure what i'm missing because i'm very new with Ajax. I just get 'success' but the field doesn't get updated. I've also tried a variation shown here https://www.youtube.com/watch?v=Z0Jw226QKAM with the same results.