0

I have used the following code on my functions.php page

add_action('woocommerce_product_thumbnails', 'my_ajax_button');

function my_ajax_button() {
echo '<button class="buy-this-room myajax" id="buy_this_room" >Buy This Room</button> 
      <button class="buy-this-design myajax" id="buy_this_design" >Buy This Design</button>';
}

add_action('wp_head', 'my_action_javascript');

function my_action_javascript() {
?>
<script type="text/javascript" >
 jQuery(document).ready(function($) {
 var ajaxurl = "<?php admin_url('admin-ajax.php'); ?>";
$('.myajax').click(function(){
    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});


});
</script>
<?php
}

add_action('wp_ajax_my_action', 'my_action_callback');

 function my_action_callback() {
 global $wpdb; // this is how you get access to the database

 $whatever = $_POST['whatever'];

 $whatever += 10;

         echo $whatever;

 exit(); // this is required to return a proper result & exit is faster than 

}

Ajax call is happening but i'm not getting the result.Alert is showing like this

Got this from the server: <!DOCTYPE html>
 <!--[if IE 7 ]><html class="ie ie7" lang="en-US"> <![endif]-->
 <!--[if IE 8 ]><html class="ie ie8" lang="en-US"> <![endif]-->
 <!--[if IE 9 ]><html class="ie ie9" lang="en-US"> <![endif]-->
 <html  lang="en-US">
 <head>

Can anybody help please!

Thanks

1 Answer 1

0

Its looks like you are not printing the admin ajax URL.

add_action('wp_head', 'my_action_javascript');

function my_action_javascript() {
?>
<script type="text/javascript" >
 jQuery(document).ready(function($) {
 var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$('.myajax').click(function(){
    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});


});
</script>
<?php
}

Please see that am printing the admin url using echo. Since there is no URL in ajax call you are getting the whole page.

Additional Info: For non logged in user, use wp_ajax_nopriv

1
  • My Pleasure. Many times this happens :)
    – WPTC-Troop
    Commented Nov 18, 2015 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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