I recently developed a small plugin for my site, that uses AJAX, and now I am trying to implement the same AJAX techniques for the same site’s templates, but I keep getting -1 as the result, here is my code,

functions.php:

    //Front end AJAX functions

    function eu_custom_query(){
        global $post;
        global $wpdb;

        echo "yo";

        die();
    }

function enque_template_scripts() {

    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://code.jquery.com/jquery-1.6.2.js');
    wp_enqueue_script( 'jquery' );


    // embed the javascript file that makes the AJAX request
    wp_register_script( 'scripts.js', get_bloginfo('template_directory').'/scripts/scripts.js');
    wp_enqueue_script( 'scripts.js' );

    // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
    wp_localize_script( 'scripts.js', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); 

}    


    add_action('wp_ajax_custom_query', 'eu_custom_query');
    add_action('wp_ajax_nopriv_custom_query', 'eu_custom_query');
    add_action('get_header', 'enque_template_scripts');

scripts.js:

$(document).ready(function(){
    $("#do_ajax").click(function(){
            $.post(wp_ajax.ajaxurl, { action: 'eu_custom_query' }, function(data){
                alert(data);
            });
    });
});

I’m using WordPress version 3.2.1

Any ideas on what I’m doing wrong?

2 Answers
2

You are passing ‘eu_custom_query’ as the action in your AJAX. It should be ‘custom_query’.

You decide the action name, when you add the action i.e. ‘wp_ajax_my_action’ would be called ‘my_action’

You are confusing it with the callback method. Hope that makes sense.

p.s. to fix your code change:

add_action('wp_ajax_custom_query', 'eu_custom_query');
add_action('wp_ajax_nopriv_custom_query', 'eu_custom_query');

to:

add_action('wp_ajax_eu_custom_query', 'eu_custom_query');
add_action('wp_ajax_nopriv_eu_custom_query', 'eu_custom_query');

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *