Search code examples
ajaxwordpressadmin-ajax

wordpress: AJAX: 400 bad request with admin-ajax.php


I have searched and red a lot of this issue. However, I do not know, why this few simple lines produce a "POST http://example.com/wp-admin/admin-ajax.php 400 (Bad Request)"

What I basically want (later on) is: If you press a button, a counter will be updated and write a value into my mySQL. But before I can think about a mySQL query, I stumble over this 400 Error.

What I have (really basic, no validations, etc.):

html

<button id="vote" type="button">Click Me</button>

jQuery

<script type="text/javascript">
//var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";  // get ajaxurl
jQuery('#vote').click(function() {
jQuery.ajax({
    url: 'http://example.com/wp-admin/admin-ajax.php', //just hard coded to see if I have a problem with my ajaxurl
    type : 'post',
    data: {
        'action' : 'ibvote'
    },
    success: function( data) {
        alert( data);}
    });
});
</script>

php

add_action("wp_ajax_ibvote", "ibvote");
add_action("wp_ajax_nopriv_ibvote", "ibvote");

function ibvote(){
    echo "DONE";
    wp_die();
}

Any help would be great. Thank you.


Solution

  • Thank you @all. I use the "Code Snippets" plugin and I activated "only run on site frontend". Today with more coffee I switched to run snippet everywhere and: voila! Working like a charm.

    @Bhautik: Again thank you for your time and answer :)