0
votes

In WordPress, I'm trying to post a jQuery variable using AJAX to use later in PHP. I've setup my jQuery function and the function to echo the variable.

I am getting the success message from the jQuery function in the console log, but the $_POST variable is null.

Below are the functions I've setup:

function foo_carousel_js() { ?>
     <script>
     jQuery(document).ready(function($) {
       var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>";
       var count_ci = $('.selector li').length;

       $.ajax({
          type: 'POST',   
          url: ajax_url,  
          data: {
            action : 'foo_item_count',
            count_ci : count_ci
          },
          success:function( data ) {
            console.log( data );
          }
       });
    });
   </script>
<?php }
add_action( 'wp_footer', 'foo_carousel_js' );

function foo_item_count() {

    $k = esc_html( $_POST['count_ci'] );
    echo $k;

    wp_die(); 
}
add_action('wp_ajax_foo_item_count', 'foo_item_count');
add_action('wp_ajax_nopriv_foo_item_count', 'foo_item_count');
1
Did you say console.log displays your count_ci value correctly in the success callback? - Tony M
@TonyM: Yes, it does. I can't figure out how the value is correctly displayed in the console but isn't in the $_POST variable. - chowwy
I know this might like a silly question: but how do you know it doesn't? echo $k; seems to be working - are you trying to access $_POST['count_ci'] ) outside of your Ajax handler function? i.e foo_item_count() - Tony M
@TonyM: What you're asking is helpful--I am trying to access/echo the $_POST variable elsewhere (outside of the handler function), but haven't been able to. - chowwy
posted an answer @chowwy, I had this exact problem a while ago - Tony M

1 Answers

1
votes

I had the exact same question/problem a few years ago. Turns out you cannot access that Ajax sent value anywhere else within WP besides your functions.php and of course plugin files. Reason being that while doing Ajax, WP only reloads the mentioned files (functions and plugins) but not the rest of the template structure. Therefore, while $_POST has your data, you can't render it on a template file because those are already loaded.

Edit:

Even within the plugin files, you only have access to your $_POST values within an Ajax handler function.

I recommend rethinking your goal, maybe Ajax isn't the way to go.