WordPress using Ajax on the front side

In this demo (put out by InkThemes) we can see a working plugin using ajax to send the information from a post, process it in php then spit it out on the front side of your website using shortcode and in this case: [hw_ajax_frontend].

make sure you open and close with php tags.

then add the javascript file (ajax.js) within a folder called js in your plugin directory.

here’s the code:


/*
Plugin Name: Ajax Demo Plugin
Plugin URI: http://www.inkthemes.com
Description: My first ajax plugin
Version: 1.0
Author: InkThemes
Author URI: http://www.inkthemes.com
License: Plugin comes under GPL Licence.
*/
// enqueue and localise scripts
wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
// THE AJAX ADD ACTIONS
add_action( 'wp_ajax_the_ajax_hook', 'vcos_ajax_action_function' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); // need this to serve non logged in users
// THE FUNCTION
function vcos_ajax_action_function(){
/* this area is very simple but being serverside it affords the possibility of retreiving data from the server, and we'll process it here then passing it back to the javascript function */
$name = $_POST['name'];
$name = "".$name." ".$name."";
echo $name;// this is passed back to the javascript function
die();// wordpress may print out a spurious zero without this – can be particularly bad if using json
}
// ADD EG A FORM TO THE PAGE
function hello_world_ajax_frontend(){
$the_form = '
<form id="theForm">
<input id="name" name="name" value ="" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" />&nbsp; <!– this puts the action the_ajax_hook into the serialized form –>
<input id="submit_button" value = “Click This" type="button" onClick="submit_me();" />
</form>
<div id="response_area"> This is where we\'ll get the response after processing
</div>';
return $the_form;
}
add_shortcode('hw_ajax_frontend', 'hello_world_ajax_frontend');

now for the javascript which you will paste into a file called ajax.js in the js directory:


function submit_me(){
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
,
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
}