Home › Forums › General Issues › Update_field() Using Ajax
Hello,
I’d like to count file download with ACF.
I have a text input set as “downloaded”, and I would like update this field every time user click download button on my single.php.
I have followed this thread but it doesn’t work for me.
Here’s my code :
Single.php (Download button)
<a id="btn-download" href="<?php the_field('source'); ?>" class="btn btn-primary btn-download mt15">Download Prototype</a>
Hidden Form
<form id="test-form" action="">
<input type="hidden" id="input-test" name="input-test" value="<?php the_field('downloaded'); ?>">
</form>
PHP (in the theme function.php)
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('downloaded', $input_test);
}
add_action( 'wp_ajax_nopriv_test_function', 'test_function' );
add_action( 'wp_ajax_test_function','test_function' );
Javascript
$("a#btn-download").click(function(){
var data_count = $('#data-download').attr('data-count');
data_count = parseInt(data_count)+1;
$('#data-download').attr('data-count',data_count);
$('#data-download').text(data_count +' downloads');
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var form = "#test-form";
$.ajax({
url: ajaxurl + "?action=test_function",
type: 'POST',
data: {'input_test_int' : $('#input-test').val()},
success: function(data) {
console.log(data);
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
Could you please suggest me to solve this problem?
You need to supply the post id to update the field on. During an AJAX request WP and ACF will not know what post you’re trying to update unless you tell it. The thread you linked to has the post id in a hidden field as well. You need to supply the post ID when updating the field
update_field($field_name, $value, $post_id);
see https://www.advancedcustomfields.com/resources/update_field/
The topic ‘Update_field() Using Ajax’ is closed to new replies.
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.