Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have create the appropriate code to handle AJAX request on WordPress but I get 0 as responce from the server.

My plugin code is here:

class my_plugin
{
    function my_plugin()
    {
        add_action('wp_ajax_do_ajax', array($this, 'do_ajax'));
        add_action('wp_ajax_nopriv_do_ajax', array($this, 'do_ajax'));
        add_action('wp_head', array($this, 'init'));
    }

    function init()
    {
        ?>
        <script type="text/javascript">
            var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
        </script>
        <?php
    }

    function do_ajax()
    {
        print_r($_POST);
        die();
    }
}

$mp = new my_plugin();

This is my jQuery code:

jQuery(document).ready(
    function($)
    {
        $.ajax(
            {
                type: "POST",
                url: ajaxurl,
                data: {action: "do_ajax", some_data: "some_value"},
                success: function(e)
                {
                    console.log(e);
                }
            }
        );
    }
);
share|improve this question

1 Answer 1

up vote 2 down vote accepted

I would recommend using a few different tools to try to debug the interaction. First of all, you can see exactly what jQuery is sending via AJAX using the debug console built in to many browsers. If all else fails, hit F12 and it will launch the console window in just about everything. If that doesn't work, install Firebug for Firefox so you have a console window.

The console will show your network activity. With the console open, refresh the page. It should log your AJAX request so you can make sure that the request is sending the data you intend to the URL you intend.

Alternatively, you can use a tool like Fiddler to intercept the request and response. You can then inspect exactly what was sent, to where, and what responded.

With that said ... there's not much more we can help you with. Here's why:

  1. You didn't give us all of the code, so we can't install your plugin on our servers to test things. Where are you calling $mp = new my_plugin();, for example? If it's not called in the right places, then your code won't fire.
  2. We don't know how your site is set up. Are you enqueueing jQuery before you try to use jQuery AJAX? What does the theme's output look like.

Number 1 in this case might be the big issue. If you're declaring a new instance of my_plugin() inside your theme, then admin-ajax.php might not even see your hooks. So, without knowing where and how you're using this code, we can't provide any help beyond suggesting debug tools.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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