Home › Forums › General Issues › Use update_field() with AJAX › Reply To: Use update_field() with AJAX
Thanks Hube2, you’re spot on. This is what worked for me:
I have a text input with the “Field Group” set as ‘test’
HTML
<form id="test-form" action="">
<input type="text" name="input-test" value="<?php the_field('test'); ?>">
<input type="submit" value="Update">
</form>
PHP (In the themes function.php file)
function test_function() {
// Set variables
$input_test = $_POST['input-test'];
// Check variables for fallbacks
if (!isset($input_test) || $input_test == "") { $input_test = "Fall Back"; }
// Update the field
update_field('test', $input_test);
}
add_action( 'wp_ajax_nopriv_test_function', 'test_function' );
add_action( 'wp_ajax_test_function','test_function' );
Javascript
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var form = "#test-form";
$(form).submit(function(event) {
event.preventDefault();
$.ajax({
url: ajaxurl + "?action=test_function",
type: 'post',
data: $(form).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.