Islam Mohamed
Islam Mohamed

Reputation: 91

Why i can't get WP custom fields value or post ID via Ajax?

I wrote a code that generate a link based on the visitor location and it worked perfectly but i discovered that the generated code get cached since i'm using a full page caching so i though to solve that issue i can use ajax to load that link. I used the below code which worked perfectly in getting some variables that i need such as location variable and link domain variable etc.. however i'm unable to get the WooCommerce custom field data or even the product id it just return blank.

I'm using this code to get the custom field which worked perfectly when used directly in function however can't get it to work in ajax

$uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );

I used that code in functions.php

add_action( 'woocommerce_before_add_to_cart_button', 'affiliate_link_ajax', 11);
function affiliate_link_ajax() {    
?>
<script>
jQuery(document).ready(function(){

             jQuery.ajax({
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                type: 'POST',
                data: {
                action: 'getmyfunctionform1'
                },
                dataType: 'html',
                success: function(response) {

                jQuery("#myResultsform1").html(response);

                }

        }); 
    });
</script> 
<!-- end Ajax call to getmyfunctionform1 smc 11-22-2013 -->

<div id="myResultsform1"></div>
<?php
}

and this code in funnctions.php as well

// Ajax Function to Load PHP Function myfunctionform1 smc 11/22/2013

add_action('wp_ajax_getmyfunctionform1', 'myfunctionform1');
add_action('wp_ajax_nopriv_getmyfunctionform1', 'myfunctionform1');

function myfunctionform1() { 
    $uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );
echo $uk_asin;
// Whatever php and or html you want outputed by the ajax call in template file

die(); } // important must use

// end Ajax Function to Load PHP Function myfunctionform1 smc 11/22/2013

I would really appreciate if the answer was simple since i'm still very new to coding

Upvotes: 3

Views: 1240

Answers (1)

Hans
Hans

Reputation: 1176

Pass your post ID to your AJAX request:

data: {
    action: 'getmyfunctionform1',
    postId: <?php echo get_post()->ID; ?>
}

And then use it in your callback function to get the meta value:

function myfunctionform1() { 
    $postId = filter_input( INPUT_POST, 'postId', FILTER_SANITIZE_NUMBER_INT );
    $uk_asin = get_post_meta( $postId, "wccaf_uk_asin", true );
    // etc.
}

Upvotes: 4

Related Questions