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?
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
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); });