Custom form validation

I have created a basic form which can be POST to admin-post.php and also submitted via an AJAX call to admin-ajax.php. Both submissions work correctly, use the nonce for a little extra security, and I can process the data as required.

My question and problem is how, with the regular form POST to admin-post.php, to send back a message to the form with either a success message string, or an error – which could be a string, or an array of invalid form field entries? With the AJAX call I can simply echo a json encoded response.

I know there is no session set unless I manually call session_start() and also using globals isn’t ideal. Is there some other sort of storage or system I can use to pass these messages?

I’ve used transients before – would these be suitable? I understand the transient data may not be available at any given moment so perhaps not?

Could I use the WP_Error class?

One Answer

Yes, you'd use a JSON response containing an error property.

echo json_encode( [
    'error' => [
        'code'    => 'my_error_code',
        'message' => 'My error message.',
        'data'    => [any additional data you need],
] );

Your AJAX callback should look for the error and adapt accordingly.

For the regular POST, you'd want to generate HTML markup that produces a WP Notice, or that produces markup that you will style as a notice. See: Complete Guide to Notices

Answered by jaswrks on November 21, 2021

Add your own answers!

Related Questions

How to make repeated component/block in Gutenberg

1  Asked on January 1, 2021 by paranoid-android


How do I get the category URL from get_the_category?

2  Asked on December 28, 2020 by egr103


$wpdb -> Batch insert from XML File?

3  Asked on December 27, 2020 by click-here


lazy load comments wordpress on click

1  Asked on December 27, 2020 by sa-eu


Hook to use when customer placing order

1  Asked on December 26, 2020 by kevsterino


WordPress Ajax Custom Query – High CPU LOAD

0  Asked on December 22, 2020 by techn9ne


Ask a Question

Get help from others!

© 2021 All rights reserved.