0

So hello I'm getting error 400. Here is my PHP and JS path to file is right. PHP

add_action("wp_enqueue_scripts", "js_enqueue_search");
function js_enqueue_search(){
    wp_register_script("search", get_stylesheet_directory_uri() . "/js/search.js", "", wp_get_theme()->get("Version"), true);
    wp_enqueue_script("search");
    wp_localize_script("search","search_x", array("ajaxurl" => admin_url("admin-ajax.php")));
}

add_action("wp_ajax_nopriv_search_data", "search_data");
add_action("wp_ajax_search_data", "search_data");
function search_data(){
    echo "test";
    wp_die();
}

JS

let ajax = new XMLHttpRequest();
ajax.open("GET", search_x.ajaxurl, true);
ajax.send();

ajax.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.ajax);
  }
};

1 Answer 1

0

i can't see the action parameter in your code

it should be:

let ajax = new XMLHttpRequest();
ajax.open("GET", search_x.ajaxurl + '?action=search_data', true);
ajax.send();

ajax.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.ajax);
  }
};

see this reference about action parameter https://codex.wordpress.org/AJAX_in_Plugins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.