0

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() { 

// 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

1

Because they're 2 different requests, and the post doesn't carry over to the AJAX request from the initial load. Nothing is remembered between page loads, and once the page is generated, nothing persists on the server. It's a clean slate every time, so why would it remember the post variable?

When you request the page, there's a post loop and a main query that WP created, and calls the the_post that set up the current post. That's why it works the first time.

But when you make your AJAX request, there's none of that, after all how is it supposed to know? Each request is isolated and its own thing. It doesn't have a URL to pull query variables from and do a query/template, in fact there is no post query in an admin AJAX request unless you do one yourself

So, the AJAX request needs the post ID, but it doesn't have that information, so send it!

        data: {
            action: 'getmyfunctionform1',
            post_id: <?php echo get_the_ID();?>
        },

You can now do $_POST['post_id']

Some further notes

Security

This is insecure:

            success: function(response) {

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

            }

Especially if you're not using SSL, anybody can intercept and insert anything into the page. Instead, it should return data, not HTML, then use the data to build the HTML in JS.

Naming

myfunctionform1 tells us nothing about what this actually does, perhaps a better name would be wccaf_uk_affiliate_link_ajax_handler?

The REST API

WP Admin AJAX is old, and when it doesn't work it's painful, a complete black box with no clues.

Why not use the simpler REST API instead?

Register an endpoint, e.g. example.com/wp-json/arabtornado/v1/affiliate_link

add_action( 'rest_api_init', function () {
        register_rest_route( 'arabtornado/v1', '/affiliate_link/', array(
                'methods' => 'GET',
                'callback' => 'arabtornado_generate_link'
        ) );
} );

Note the callback arabtornado_generate_link, that's the function that does the work:

function arabtornado_generate_link( $request ) {
    $post_id = $request['post_id'];
    // etc.. generate response
    $result = "https://example.com/affiliate";
    return $result;
}

Hey presto:

var url = 'https://example.com/wp-json/arabtornada/v1/affiliate_link?post_id=1';
jQuery.get( url ).done( function( data ) {
    jQuery("#myResultsform1").text( data );
}).fail( function() {
    jQuery('#myResultsform1').text("couldn't contact server");
});

If it doesn't work, it'll just tell you what the problem was in the response so look at the network panel in your browsers dev tools

  • Thanks so much for your answer, I'm sorry, i'm still very new to coding. I though i can echo any code in arabtornado_generate_link() function but i tried that but didn't work, i get "couldn't contact server if i put any code ex. echo "test"; actually i have a fairly long code in a function that is responsible of generating the code in a specific way. I was wondering if there is a way to render the result of that function or call that function or a way to place the content of that function into arabtornado_generate_link() Here is the func that generate the link snippi.com/s/ctolmmw – arabtornado Sep 22 '18 at 19:30
  • @arabtornado you cannot rely on get_post in an Admin AJAX call like that. As I said, every request is a fresh slate, nothing carries over from one request to another as you expect it to. I'm not going to go through your code and give you a fixed version though, that would neither answer the question or explain what the problem was. If you have a good grasp of the fundamental basics of PHP variables and simple functions then you should know what to do, regardless of how familiar with WordPress you are. Just try to understand that everytime you make a request, it's starting from scratch – Tom J Nowell Sep 23 '18 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.