How to Use AJAX in WordPress Development. The Quick-and-Dirty QuickStart Guide
Edit: Enjoyed this? Check out my new post on AJAX using JSONP in WordPress.
There are some great posts and a fantastic wiki page explaining how to use AJAX in WordPress. But I haven’t found a quick plug-and-play tutorial. So here goes…
The problem: A simple form that will give the visitor an input and when they click “Next” it will send the content of the input to the server who will send all the $_POST fields back as JSON. Why you’d want this? Who knows. But it’s a simple problem to solve that you can adopt to do anything.
Here’s the Gist
(function ($) { $(document).ready(function () { $('#next').click(function () { $.post( PT_Ajax.ajaxurl, { // wp ajax action action: 'ajax-inputtitleSubmit',
// vars title: $('input[name=title]').val(),
// send the nonce along with the request nextNonce: PT_Ajax.nextNonce }, function (response) { console.log(response); } ); return false; });
}); })(jQuery);
admin\_url( 'admin-ajax.php' ), 'nextNonce' => wp\_create\_nonce( 'myajax-next-nonce' ) ) ); } function myajax\_inputtitleSubmit\_func() { // check nonce $nonce = $\_POST\['nextNonce'\]; if ( ! wp\_verify\_nonce( $nonce, 'myajax-next-nonce' ) ) { die ( 'Busted!' ); } // generate the response $response = json\_encode( $\_POST ); // response output header( "Content-Type: application/json" ); echo $response; // IMPORTANT: don't forget to "exit" exit; } [page-ajax\_input.php](https://gist.github.com/jackreichert/5233481#file-page-ajax_input-php)