Create Proper WordPress Ajax Request in JavaScript, NOT jQuery

Question

Okay, so I programmed the following ajax code for my plugin, and I’m wondering why it’s not working:

JavaScript:

function myFunction() {

  let dataContent = "hello";

  let myData = {
    // Nonce
    _ajax_nonce: "<?php wp_create_nonce( 'nonce-name' );?>",
    // Action Hook name for Ajax Call
    action: 'my_action',
    // Currently typed username
    data: dataContent
  };
  // To send the JavaScript object to the server, convert it into a JSON string
  let myDataJSON = JSON.stringify(myData);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      alert(this.responseText);
    }
  };
  let link = "<?php admin_url( 'admin-ajax.php' );?>";
  xhttp.open("POST", link, true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("data=" + myDataJSON);
}

PHP (Callback):

function answer() {
  check_ajax_referer( 'nonce-name' );
  echo "hello";
}

PHP (Hook):

add_action( 'wp_ajax_my_action', 'answer' );

When launching the call, I get “undefined” displayed in the alert window. What’s wrong?

0
, , Joe 7 months 0 Answers 92 views 0

Leave an answer