Wordpress Ajax Frontend
The ajaxurl is not exposed to front end by default, so lets add it to the header first.
function set_ajaxurl(){
echo '<script type="text/javascript"> var _ajaxurl = "'.admin_url("admin-ajax.php").'";</script>';
}
add_action( 'wp_head', 'set_ajaxurl' );
And then we make a action function for our ajax
function ajax_action(){
//do something with the $_POST data here
//like you do with normal WordPress stuffs
exit(); //this is needed
}
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action' );
Take note of the wp_ajax_nopriv_ajax_action the “nopriv” makes it available to non logged in users. If you want to make you script work for logged in users as well, you need to duplicate your hook with the normal wp_ajax_ajax_action like so.
add_action( 'wp_ajax_ajax_action', 'ajax_action' );