Categories
Web Development WordPress

WordPress: How to send data and variables from js to PHP in an AJAX call

In this post we will learn ways to run a PHP function from JQuery and then from react.

First the JQuery:

jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {
            action: "my_user_vote",
            nonce: nonce
         },
         success: function(response) {
            if(response.type == "success") {
               jQuery("#vote_counter").html(response.vote_count)
            }
            else {
               alert("Your vote could not be added")
            }
         }
      })   

   })

I’m sure many of you recognize the javascript code block above, added to your code to call an AJAX function and run a PHP function from javascript. The above code will call the PHP function my_user_vote() when an action picked up by JQuery takes place if the function exists, the AJAX hooks were added correctly and the script was in fact localized with the ajaxurl.

If we want to pass data from the original JQuery function that calls the PHP function TO that PHP function, we can simply add more ‘data’ to the call and that data/those variables will be accessible in the PHP as $_POST variables in the function that is called with the names the data was given in the data part of the call.

data : {
            action: "my_user_vote",
            nonce: nonce,
            myVariable: "foobar"
         },

Now, in my PHP function I can get the value “foobar” simply by

public function my_user_vote() {
     $my_variable = wp_unslash( wp_kses_post( $_POST'myVariable'] ) );
...
}

Now from React:

Inside the React element that you wish to send the request from we first define a function that will send a request to a specific endpoint and pass the PHP function a variable called “answers”. Define the following new function in the React element:

const run_algorithm = async () => {
  try {
      const formData = new FormData();
      formData.append('answers', JSON.stringify(answers));

      const response = await fetch('/wp-json/v1/run_algorithm', {
          method: 'POST',
          body: formData,
      });

      const responseData = await response.text();
      console.log(responseData);
  } catch (error) {
      console.error('Error calling PHP function:', error);
  }
};

Then in the return for that element, call the function. In this case we will call the PHP function when a button in react is pushed:

return (
  <>
  <div>
      <button onClick={run_algorithm}>Run PHP Algorithm</button>
  </div>
.
.
.

Finally we will do two things in the PHP. Firstly we will register a new REST endpoint and we will specify the callback function to be run when that endpoint is hit (in this case by the React request):

add_action('rest_api_init', function () {
  register_rest_route('/v1', '/run_algorithm', array(
      'methods' => 'POST',
      'callback' => 'run_algorithm',
  ));
});

Secondly we ill define the actual callback function that is hit by the REST endpoint:

function run_algorithm() {

  // pass the answers from the react
  $answers = wp_unslash(wp_unslash($_POST['answers']));

  // Return a response or print the answers for demo purposes
  return $answers;
}

These are not the only ways to send an asynchronous request from js that runs a PHP function using the REST API in WordPress but these are two possible methods that can be used depending on the structure of the project.

Leave a Reply