I can’t get a return value from Ajax

I have an HTML form that is used to send messages to a back end server. When the user clicks the send button, it triggers a javascript that makes an Ajax call to WordPress which in turn, makes an API call to the back end server to send the message. This part works flawlessly. The server then responds with a string which I want to return to the javascript to display in the form.

For some reason, I can’t get the return value to javascript. I’ve stripped my function down to bare bones as follows:

function smsgte_admin_send() {
check_ajax_referer(‘smsgte_nonce’, ‘security’);
$response = admin_server_send(filter_input(INPUT_POST, ‘message’, FILTER_SANITIZE_STRING));

$result = array (
//’response’ => $repsonse,
‘response’ => ‘just a response’,
);

return $result;
}

The admin_server_send triggers the message being sent to the server. The message reaches the server, so that’s working. I was questioning the response from the server, so I just populated my result array with a random string, but the javascript never receives the string.

The javascript code is:

function smsgteAdminSend(button) {
var message = document.getElementById(“smsgte_admin_message”).value;

jQuery(document).ready(function ($) {
var data = {
‘action’: ‘smsgte_admin_send’,
‘message’: message,
‘security’: smsgte_Ajax.ajax_nonce,
};
jQuery.post(smsgte_Ajax.ajaxurl, data, function (response, status) {

document.getElementById(“smsgte_admin_send_response”).innerHTML = response.response;

});
});

}

Originally, I was sending the response as a string instead of a key/value pair, but that wasn’t working either. Can’t help think I’m missing something simple.

Read more here:: I can’t get a return value from Ajax

Leave a Reply

Your email address will not be published. Required fields are marked *