The values are not passed as parameters, but passed in the $_POST
array.
- You need to add nonce for security using
check_ajax_nonce
https://developer.wordpress.org/reference/functions/check_ajax_referer/ - You need to sanitize values submitted before inserting into database
Here’s how this should be done:
add_action( 'wp_ajax_send_projectmessage', 'send_projectmessage' );
function send_projectmessage() {
global $wpdb;
check_ajax_referer( 'send_projectmessage', 'send_projectmessage_nonce' );
$projectid = sanitize_text_field( $_POST['projectid'] );
$userid = sanitize_text_field( $_POST['userid'] );
$message = sanitize_text_field( $_POST['message'] );
$wpdb->insert( 'tbl_messages', array(
'project_id' => $projectid,
'user_id' => $userid,
'message_body' => $message
) );
wp_send_json_success();
}
I also don’t recommend submitting the userid
via the POST as that allows users to define it themselves. If this is the WordPress user ID you should instead use internal core function to obtain that value:
add_action( 'wp_ajax_send_projectmessage', 'send_projectmessage' );
function send_projectmessage() {
global $wpdb;
check_ajax_referer( 'send_projectmessage', 'send_projectmessage_nonce' );
$user_id = get_current_user_id();
if ( empty( $user_id ) ) {
wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );
return;
}
$projectid = sanitize_text_field( $_POST['projectid'] );
$message = sanitize_text_field( $_POST['message'] );
$wpdb->insert( 'tbl_messages', array(
'project_id' => $projectid,
'user_id' => $user_id,
'message_body' => $message
) );
wp_send_json_success();
}
For the nonce, see here:
https://codex.wordpress.org/WordPress_Nonces
https://codex.wordpress.org/Function_Reference/wp_nonce_field
Somewhere on the page you need to include that hidden nonce field:
<?php wp_nonce_field( 'send_projectmessage', 'send_projectmessage_nonce' ); ?>
And make sure to include it in the POST:
$('#form-pm').on('submit',function(e) {
e.preventDefault();
var send_projectmessage_nonce = $('#send_projectmessage_nonce').val();
//hardcode stuff for testing
var testdata = {
'action': 'send_projectmessage',
'projectid': '71',
'userid': '1',
'message': 'voila',
'send_projectmessage_nonce': send_projectmessage_nonce
};
var ajaxRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: testdata
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});