Best way to handle a form post in plugin

Ok – I finally found a way to do this – and I believe it can be seen as a best practice…

I wanted to post with jQuery from a form on the WP front end. Was a lot easier than I expected.

First of all, make sure you have javascript to capture the form event (when a user presses the submit button). Post the form to the wordpress file admin-ajax.php – found using:

admin_url('admin-ajax.php')

And – this is important – make sure you add a parameter called “action” in the post request. The value of “action” will be used to name the wp-function you will use as callback (or form handler).

Let’s say you give the action parameter a value of “my_callback”. You would then create the two actions:

add_action( 'wp_ajax_my_callback', 'my_callback_function' );
add_action( 'wp_ajax_nopriv_my_callback', 'my_callback_function' );

Then – simply create the function my_callback_function() – and you are free to use any $_POST data in it.

What you echo out in that function will be returned to the initial jQuery request

error code: 523