0

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?

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

  • Sorry if I wasn't clear but I have already done the AJAX method, I just need a way to display a message (error / or success) for the admin-post.php call. Admin notices can't be used on the front-end can they? – Alexander Holsgrove Nov 8 '17 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.