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?
Yes, you'd use a JSON response containing an
<?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.
Answered by jaswrks on November 21, 2021
1 Asked on January 1, 2021
1 Asked on January 1, 2021 by paranoid-android
1 Asked on December 31, 2020 by macman
1 Asked on December 31, 2020 by wp_boss
0 Asked on December 30, 2020 by stanislaw
1 Asked on December 28, 2020 by sandy
2 Asked on December 28, 2020 by egr103
3 Asked on December 27, 2020 by click-here
0 Asked on December 27, 2020
3 Asked on December 27, 2020 by the-chewy
1 Asked on December 26, 2020 by kevsterino
2 Asked on December 26, 2020 by craig
1 Asked on December 26, 2020 by gerald
1 Asked on December 26, 2020 by usman-khan
0 Asked on December 26, 2020 by nbowdski
1 Asked on December 24, 2020 by hesham-shawky
1 Asked on December 23, 2020 by stefan-avramovic
0 Asked on December 22, 2020
Get help from others!