I have this:


add_action('wp_ajax_count_messages', 'count_messages');
function count_messages($projectid) {
    //some code


var countData = {
    'action': 'count_messages',
    'projectid': '100'
var myRequest =
        url: admin_ajax.ajax_url,
        type: 'post',
        data: countData
myRequest.done(function(data){ console.log(data); });

When I check console, I get:

{success: true, data: ""}

I am not sure what is happening and why I get an empty string?


The data you send from jQuey to PHP is in the $_POST variable. So you can use $_POST['projectid'] inside your PHP function to get the data.


Have you considered using a REST API endpoint instead?

e.g. lets register our endpoint:

add_action( 'rest_api_init', function () {
        register_rest_route( 'rollor/v1', '/count_messages/', array(
                'methods' => 'GET',
                'callback' => 'count_messages'
        ) );
} );

Then the implementation:

function count_messages($request) {
    return $request['projectid'];

Now you can visit yoursite.com/wp-json/rollor/v1/count_messages?projectid=123

Adding Validation

We can even extend it to add built in validation, and put the project ID in the URL:

        register_rest_route( 'rollor/v1', '/count_messages/(?P<projectid>\d+)', array(
                'methods' => 'GET',
                'callback' => 'count_messages',
                'args' => array(
                    'projectid' => function($param,$request,$key) {
                        return is_numeric($param);
        ) );

Now we can visit yoursite.com/wp-json/rollor/v1/count_messages/123. It will even tell us if we got it wrong in plain english.

And finally:

var myRequest =
    url: 'https://example.com/wp-json/rollor/v1/count_messages/' + projectid,
myRequest.done(function(data){ console.log(data); });
  • 1
    thank you. I am now trying to port all my code into REST, because unlike classic admin-ajax.php, it is actually fun to debug wow – Rollor Feb 23 at 17:44
  • Is there a quick and clean way to make $current_user, or get_current_user_id(), or a workaround, to work with REST API? – Rollor Feb 23 at 20:50
  • It should work the same way as any other, but if you're needing to implement user auth, the API can handle that with the appropriate arguments when you register it, you should not need to do any validation or auth checking in the endpoint function itself – Tom J Nowell Feb 24 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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