14

I've setup the basic wordpress ajax example in my wp theme. The trigger is made by modernizr.js checking the media queries on the page.

jQuery(document).ready(function($) {
    if(Modernizr.mq('only all and (max-width:6300px)')) {
        var data = {
        action: 'my_action',
        whatever: ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
        jQuery.post(ajax_object.ajax_url, data, function(data) {
            $("#trending-Container").html(data).fadeIn(1000);
        });
    }

});//end function 

I have localized and enqueue'd my scripts.

wp_enqueue_script('mainJS', get_template_directory_uri() . '/js/mainJS.js', array("jquery") );
wp_localize_script( 'mainJS', 'ajax_object', 
                    array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );

and finally the function that handles the request is:

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
        global $wpdb;
            $whatever = intval( $_POST['whatever'] );
            $whatever += 10;
                echo $whatever;
            die();

        }

This constantly gives me a response of 0 (no properties) and I do not know why. P.S This is all local.

Status code 200
Host:lart.co.uk
Origin:http://lart.co.uk
Referer:http://lart.co.uk/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:my_action
whatever:1234
8
  • Can you check exit(intval( $_POST['whatever'] )); ?
    – The Alpha
    Commented Oct 14, 2013 at 22:33
  • @RecoveringSince2003 You mean instead of die()? I tried and still nothing.
    – UzumakiDev
    Commented Oct 14, 2013 at 22:36
  • Try print_r($_POST);die(); to make sure $_POST is not empty, contains the value.
    – The Alpha
    Commented Oct 14, 2013 at 22:38
  • It's still 0, I deleted all of the my_action_callback() function and it responded 0. Is the function handler not being triggered by the add_action?
    – UzumakiDev
    Commented Oct 14, 2013 at 22:43
  • It should trigger according to the code you've posted.
    – The Alpha
    Commented Oct 14, 2013 at 22:47

3 Answers 3

32

Everything has to match here:

PHP

add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {}

JS

var data = {
    action: 'my_action',
    whatever: ajax_object.we_value 
};

Also, you're missing security checks and a better handling of the response.
Check this examples: [ 1 ] and [ 2 ].

3
  • Still nothing. I didn't think the other "my_action" had to match and could just be the name of the function?
    – UzumakiDev
    Commented Oct 15, 2013 at 2:06
  • 1
    Example #2 is pretty simple, did you try to adapt it?
    – brasofilo
    Commented Oct 15, 2013 at 2:36
  • ah, thanks. After looking at example 2 I was able to adapt the code and get it to output correctly. Anyway thanks :)
    – UzumakiDev
    Commented Oct 15, 2013 at 12:15
7

Add the "exit" end of the function as shown below, this will fix the return 0 with the response in WordPress on using the ajax request.

add_action('wp_ajax_nopriv_getStateList', 'getStateList');
add_action('wp_ajax_getStateList', 'getStateList');

function getStateList() {
    global $wpdb;
    $countryId = $_POST['countryId'];
    $results = $wpdb->get_results("SELECT id,name FROM regions where country_id ='".$countryId."' ");
    echo json_encode(array('status'=>200,'data'=>$results));
    exit;
}
2
  • Thanks for the answer. Maybe you can add some explanation about what this changes for fixing the problem?
    – Fabian S.
    Commented Sep 27, 2017 at 9:15
  • 2
    I have edited the comments, you can see above. For your FYI, this will stop to return 0 with the response in WordPress on using the ajax request.
    – abrar
    Commented Sep 27, 2017 at 12:51
2

Here is the full example to solve this issue:

JavaScript:

$(document).ready(function() {
    $("#submit").click(function(e) {
        var demo = 'demo';
        var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
        data = { action: "data_insert", demo: demo};     
        $.ajax({
            url: ajaxurl,
            data: data,
            dataType: 'json',
            type: 'post',
            success: function(response) {
              console.log(response);  
            }
        });
    });    
});

PHP:

add_action('wp_ajax_data_insert', 'data_insert');
add_action('wp_ajax_nopriv_data_insert', 'data_insert');
function data_insert() {
    $data = $_POST['demo'];
    echo json_encode($data);
    die();
}

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