errors - Custom form validation

admin2025-01-07  8

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?

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?

Share Improve this question asked Nov 7, 2017 at 20:46 Alexander HolsgroveAlexander Holsgrove 1,9091 gold badge15 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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

<?php
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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736255467a284.html

最新回复(0)