Home › Forums › Front-end Issues › Field Content is not loading from Ajax call › Reply To: Field Content is not loading from Ajax call
So, what you need to do is to localize the script. For a JS file you would use this https://developer.wordpress.org/reference/functions/wp_localize_script/
With the script being output to the page what you can do is just echo out the post ID, see my additions.
function add_this_script_footer(){
// reference global
global $post;
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// output post id to page
var post_id = <?php echo $post->ID; ?>;
$( 'a[name=view-button]' ).on('click', function() {
var activeView = $(this).data('value');
console.log(activeView);
$.ajax({
type: 'GET',
url: '<?php echo admin_url('admin-ajax.php');?>',
data: {
'action':'toggle_view',
'activeView' : activeView,
// pass post ID back in AJAX Request
'post_id': post_id
},
success:function(data) {
$("#view-container").html(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
});
</script>
<?php }
Then in the template part you need to see if an ajax request is being done and if it is then get the post ID.
// assign post ID from global not doing ajax
// and from request if you are
$post_id = false;
if (defined('DOING_AJAX') && DOING_AJAX) {
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
}
} else {
$post_id = $post->ID;
}
Then in all of the ACF function calls you supply the post id
$value = get_field('field-name', $post_id);
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.