I have a custom plugin with the following code
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "gift_card_redeem", WP_PLUGIN_URL.'/plugin-folder/gift_card_redeem.js', array('jquery') );
wp_localize_script( 'gift_card_redeem', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'gift_card_redeem' );
}
add_action("wp_ajax_gift_card_redeem", "gift_card_redeem");
function gift_card_redeem(){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
error_log("test !empty");
$result['type'] = "success";
$result = json_encode($result);
echo $result;
}
else {
error_log("test else");
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
and a js file in the plugin called gift_card_redeem.js
jQuery(document).ready(function () {
jQuery(".redeem_gift_card").click(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: myAjax.ajaxurl,
data: { action: "redeem_gift_card" },
success: function (response) {
if (response.type == "success") {
jQuery("#test").html(response);
} else {
alert("something broke");
}
},
});
});
});
and my php and html on the form-checkout page is as follows
<?php
$link = admin_url('admin-ajax.php?action=gift_card_redeem');
echo '<a class="redeem_gift_card" href="' . $link . '" >test</a>';
?>
<h1 id="test">Test</h1>
I am getting a 400 bad request error for admin-ajax.php and I am not quite sure why. Any help would be greatly appreciated.
Thanks