loading...

2021-10-08

Two ways to sending data to backend

Two ways to sending data to backend

We’ll start with the class-based approach, which is closer to my heart. You will need composer installed and configured. Not sure how to do that? Check out this article.

Let’s get to work. We’re going to issue ourselves an endpoint to the REST API. How? Very simply:

<?php

namespace Example\API;

class API
{
  private $namespace = 'api/v1';
  private $route = 'example/create';

  public function __construct()
  {
    add_action('rest_api_init', [$this, 'generate_endpoint']);
    add_filter('rest_api_route_example_uri', [$this, 'generate_route']);
  }

  public function callback($request): \WP_REST_Response
  {
    $params = $request->get_params();
    $response = ['message' => 'Hello world!']

    return new \WP_REST_Response($response, 200);
  }

  public function generate_endpoint()
  {
    register_rest_route(
      $this->namespace,
      $this->route,
      [
        'methods' => ['POST'],
        'callback' => [$this, 'callback'],
        'permission_callback' => function (\WP_REST_Request $request) {
          return true;
        },
        'args' => [
          'id' => array(
            'validate_callback' => function($param, $request, $key) {
              return is_numeric( $param );
            }
          ), 
        ]
      ]
    );
  }

  public function generate_route(): string
  {
    return get_rest_url(NULL, $this->namespace.'/'.$this->route);
  }
}

Complicated? Not at all!
See in __constructor we execute:

  1. add_action – we initialize an endpoint that will be visible to the REST API
  2. add_filter – we generate ourselves a link that will be used in the application

If you know what is going on in __construct then now the meat.

The public function generate_endpoint executes the register_rest_route() function to generate the link.

The function register_rest_route(string $namespace, string $route, array $args = []) takes as parameters. Now we’ll take a look at $args what’s going on there. It accepts an array that consists of:

  • methods – query method [’POST’, 'GET’]
  • callback – function that will execute when the query is executed
  • permission_callback – function that usually checks if the user is logged in or wp_nonce
  • args – arguments defined, e.g. id validated as a numeric value

Now the same thing only done functionally:

add_action('rest_api_init', [$this, 'generate_endpoint']);
add_filter('rest_api_route_example_uri', [$this, 'generate_route']);

function callback($request)
{
  $params = $request->get_params();
  $response = ['message' => 'Hello world!'];

  return new \WP_REST_Response($response, 200);
}

function generate_endpoint()
{
  register_rest_route(
    'api/v1',
    'example/create',
    [
      'methods' => ['POST'],
      'callback' => 'callback',
      'permission_callback' => function (\WP_REST_Request $request) {
        return true;
      },
      'args' => [
        'id' => array(
          'validate_callback' => function ($param, $request, $key) {
            return is_numeric($param);
          }
        ),
      ]
    ]
  );
}

function generate_route()
{
  return get_rest_url(NULL, 'api/v1/example/create');
}

And which one is better? In my opinion, it’s classier, but of course you may have a different opinion! That’s the beautiful thing about programming.
Now for the second way to make a query. For this you need a link, which you can create with:

<?php

function load_admin_js() {
  wp_localize_script( 'admin-scripts', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce('ajaxnonce')
  ));
}

add_action('wp_enqueue_scripts', 'load_admin_js', 100);

Execution of the function

<?php

namespace Example\API;

class API
{
  public function __construct()
  {
    add_action('admin_post_nopriv_example', [$this, 'example']);
    add_action('admin_post_example', [$this, 'example']);
  }

  public function example()
  {
    $example = true;
    
    if($example){
      echo json_encode(['success' => true, 'data' => 'Example is true!']);
    }

    return 0;
  }
}

Now notice the __constructor here we have 2 executions of add_action. admin_post_nopriv_example and admin_post_example. As you can see in the documentation example appears in these hooks as an action. This is the action you need to pass using, for example, JavaScript [example execution below]. First, an example using a function. See how simple it is:

add_action('admin_post_nopriv_example', 'example');
add_action('admin_post_example', 'example');

function example()
{
  $example = true;
    
  if($example){
    echo json_encode(['success' => true, 'data' => 'Example is true!']);
  }
    
  return 0;
}

Uff came out long, but important. Now for dessert axios. You know it? It’s great!

import axios from "axios";

let data = new FormData();
data.append('action', 'example');
  
axios
  .post(
    ajax.url,
    data
  )
  .then((response) => {
     console.log(response)
  });
Posted in Bez kategorii