How can i get the same ajax result using WP REST API instead of admin-ajax?

I have been told that admin-ajax is outdated now and it’s better to use REST API instead but I was wondering how can I get the same result of this code which generates a button with a link based on some variables and custom fields using REST API?

also, someone told me that this code is not secure because I’m using HTML response instead of data in ajax but I’m wondering how to use data for this code?

I apologize but i’m still very new to coding

add_action( ‘woocommerce_before_add_to_cart_button’, ‘simple_amz_link_ajax’, 10);

function simple_amz_link_ajax() {
?>
<script>

jQuery(document).ready(function(){

jQuery.ajax({
url: “<?php echo admin_url(‘admin-ajax.php’); ?>”,
type: ‘POST’,
data: {
action: ‘getmyfunctionform1’,
postId: <?php echo get_post()->ID; ?>
},
dataType: ‘html’,
success: function(response) {

jQuery(“#buy_amz_btn_wrap”).html(response);

}

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

<div id=”buy_amz_btn_wrap”> Loading … </div>

<?php
}

// Amazon Simple Button Function

add_action(‘wp_ajax_getmyfunctionform1’, ‘myfunctionform1’);
add_action(‘wp_ajax_nopriv_getmyfunctionform1’, ‘myfunctionform1’);

function myfunctionform1() {
$postId = filter_input( INPUT_POST, ‘postId’, FILTER_SANITIZE_NUMBER_INT );
$country_code = $_SERVER [“HTTP_CF_IPCOUNTRY”];
$de_asin = get_post_meta( $postId, “wccaf_de_asin”, true );
$uk_asin = get_post_meta( $postId, “wccaf_uk_asin”, true );

$not_avilable_country = ‘<div id=”amz_not_avilable” class=”amz_not_avilable”>This product is not avilable in your country yet</div>’;

//////////////////////////////////////////////

if ($country_code==”DE” or $country_code==”DE”) {
$amazon_domain = ‘https://www.amazon.de’;
$associate_id = ‘bonstato-21’;
$asin = $de_asin;
}

else if ($country_code==”GB” && $uk_asin!==””) {
$amazon_domain = ‘https://www.amazon.co.uk’;
$associate_id = ‘bonmedico-21’;
$asin = $uk_asin;
}

///////////////////

global $post;
$product = wc_get_product( $postId );
$type = $product->get_type();
if( $type == ‘simple’ && $asin!=”” ){

// Amazon Link For Mobile
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/dp/<?php echo $asin ?>/?tag=<?php echo $associate_id ?>’;
}
</script>
<?php

?>
<div class=”buy_amz_btn_wrap” >
<button type=”button” id=”buy_amz_btn” class=”buy_amz_btn” onclick=”amzGo();”><i class=”fa fa-amazon fa-amz”></i><?php echo $amz_btn_title ?></button>
</div>
<?php
}

else if( $type == ‘simple’ && $asin==”” ){
echo $not_avilable_country;
}

die();

}
?>

Read more here:: How can i get the same ajax result using WP REST API instead of admin-ajax?

Leave a Reply

Your email address will not be published. Required fields are marked *