TransWikia.com

What's the right way to validate JSON data coming from an AJAX POST request?

WordPress Development Asked by Life after Guest on November 21, 2021

I’m building a little plugin with a send button: when clicked, the button calls (from the admin area) a rest api endpoint, passing JSON data through AJAX. Everything works very well and the callback correctly receives the JSON data.

Now, I want to validate the data using the validate_callback function.

Problem is I only could find examples where they validate an API parameter, and I have no parameter in my API.

A typical example:

 register_rest_route( 'route/v1', '/endpoint/', array(
'methods' => 'POST',
'callback' => array( $this, 'endpoint_post_handler' ),
'permissions_callback' => 'is_user_logged_in',
'args' => array(
    'first_name' => array(
        'required' => true,
        'type' => 'string',
        'description' => 'The client's first name',
    ),
)

) );

Here the developer is validating the first_name parameter, for example.

This is another example, from the official docs:

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/author/(?P<id>d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
    'args' => array(
      'id' => array(
        'validate_callback' => function($param, $request, $key) {
          return is_numeric( $param );
        }
      ),
    ),
  ) );
} );

What if I have no parameter at all but I still want to validate the request content?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP