0

I'm trying to send ajax requests from a React.js app to wordpress's admin-ajax.php. Here is a mini test plugin I wrote to test this:

// plugins folder > xhrLink/xhrLink.php
<?php

/*
Plugin Name: Xhr Link
*/

function basicPage() {
  echo "<h1>Admin Page</h1>";
}

function setupParams() {
  add_options_page('XHR Link', 'XHR Link', 'manage_options', 'xhr-link',  'basicPage');
}
add_action('admin_menu', 'setupParams');


function handleXhrLink() {
  wp_send_json('this response came from the back end');
}
add_action('wp_ajax_xhrLink', 'handleXhrLink');


// theme folder > functions.php
function add_cors_http_header() {
  header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');

In the React.js app I have the following function set to fire on the onClick attribute of a button:

const sendXhrLinkRequest = () => {
      let form_data = new FormData;
      form_data.append('action', 'xhrLink');

      axios
        .post('http://localhost/wptest2/wp-admin/admin-ajax.php', form_data)
        .then(response => {
          console.log(response, `=====sendXhrLinkRequest response=====`);
      });

  };

From WordPress AJAX with Axios:

FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

After clicking the button the Chrome console shows this:

VM596:1 POST http://localhost/wptest2/wp-admin/admin-ajax.php 400 (Bad Request)
(anonymous) @ VM596:1

VM596:1 XHR failed loading: POST "http://localhost/wptest2/wp-admin/admin-ajax.php".

createError.js:16 Uncaught (in promise) Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:59)

Does anyone know what causes these errors and how to handle them?

Also tried:

  • Submitting the form data as a JSON object. Same console entries resulted.
0

Solved by adding an action to handle unauthenticated users:

add_action('wp_ajax_nopriv_xhrLink', 'handleXhrLink');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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