This below is the ajax code in javascript for wordpress. Wordpress recommends jQuery, but I use the code described below and I need this one (no jQuery). Ajax sends the code and saves it in the database, it works properly (I tested), but if I want to retrieve the response from the server (this.responseText) ..., I don't get any response, just an empty alert. Why?
somepage.php:
<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here
function my_action_javascript() {
?>
<script>
// Upload file
var sendtext = "sendreceive";
var formData = new FormData();
formData.append("SENDTEXT", sendtext);
formData.append("action", "my_action_send_receive");
// Send request with data
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
alert("response from server"+this.responseText);
}
}
xmlhttp.open("POST", "<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>", true);
xmlhttp.send(formData);
</script>
<?php
}
?>
functions.php:
<?php
add_action( 'wp_ajax_my_action_send_receive', 'send_receive' );
function send_receive() {
if(isset($_POST['SENDTEXT'])){
$sendtext = $_POST['SENDTEXT'];
$response = $sendtext;
echo $response;
}
exit;
wp_die();
}
?>