This is the barebones for an AJAX call and response. Take a look and make sure this is working on Chrome and Firefox for you — works for me.
<?php
// Some function for data we'll pass
function dgx_donate_get_countries_requiring_postal_code()
{
return "cc postal code stuff...";
}
// Register everything
add_action('init', function () {
// Add required scripts
wp_enqueue_script('jquery');
$script_url = plugins_url('/js/seamless-donations.js', __FILE__);
wp_register_script('seamless_javascript_code', $script_url, array('jquery'), false);
wp_enqueue_script('seamless_javascript_code');
// Localize our data
wp_localize_script(
'seamless_javascript_code', 'dgxDonateAjax',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('dgx-donate-nonce'),
'postalCodeRequired' => dgx_donate_get_countries_requiring_postal_code()
)
);
// Register AJAX handlers
add_action('wp_ajax_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');
add_action('wp_ajax_nopriv_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');
// AJAX handler (PRIV / NO PRIV)
function dgx_donate_paypalstd_ajax_checkout()
{
// If we fail don't be silent
$fail_message="";
if (empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'dgx-donate-nonce')) $fail_message="Bad Nonce";
if (empty ($_POST['action'])) $fail_message="Missing Action";
if ($_POST['action'] !== 'dgx_donate_paypalstd_ajax_checkout') $fail_message="Bad Action";
// We failed, let em know...
if (!empty ($fail_message)) {
wp_send_json_error(array(
'message' => $fail_message
)); // die
}
// Do logic stuff
// Send the Success Response
wp_send_json_success(array(
'action' => $_POST['action'],
'message' => 'Checkout Complete',
'postalCodeRequired' => $_POST['postalCodeRequired'],
'ID' => 1
)); // die
}
});
// Shortcut to trigger AJAX call on page load
add_action('wp_footer', function () { ?>
<script>
(function ($) {
var data = {
action: 'dgx_donate_paypalstd_ajax_checkout',
nonce: dgxDonateAjax.nonce,
postalCodeRequired: dgxDonateAjax.postalCodeRequired,
};
$.ajax({
type: 'POST',
url: dgxDonateAjax.ajaxurl,
data: data,
success: function (response) {
// look at the response
if (response.success) {
// succcess data
console.log(response.data);
} else {
// no good
console.log(response);
}
}
});
})(jQuery);
</script>
<?php });