How to pass parameters from jQuery ajax into PHP function?

admin2025-06-02  3

I have this:

PHP:

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

JS:

var countData = {
    'action': 'count_messages',
    'projectid': '100'
}
var myRequest =
    $.ajax({
        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?

I have this:

PHP:

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

JS:

var countData = {
    'action': 'count_messages',
    'projectid': '100'
}
var myRequest =
    $.ajax({
        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?

Share asked Feb 22, 2019 at 19:13 RollorRollor 1291 gold badge4 silver badges10 bronze badges
 | 

2 Answers 2

Reset to default 0

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/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/wp-json/rollor/v1/count_messages/123. It will even tell us if we got it wrong in plain english.

And finally:

var myRequest =
$.ajax({
    url: 'https://example/wp-json/rollor/v1/count_messages/' + projectid,
});
myRequest.done(function(data){ console.log(data); });
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748875456a314447.html

最新回复(0)