Implementing Ajax in WordPress Themes and Plugins

Ajax is very useful when you want to execute a php script within an html without the need to reload the page.
It is easy to implement this within wordpress.
First, create a php function for the actions that will be executed.

function myAjax1()
{
	$name = $_POST['name'];
	echo '<h1>Hello '.$name.'!</h1>';
	exit;
} // end myAjax1

Second, create a php function where you’ll define the scripts.

function myAjax2()
{
?>
<script type="text/javascript">
	var $jx = jQuery.noConflict();
	var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';

	/**
	 * called when an element is clicked
	 * <input type="text" name="myname" />
	 * <a href="#" onclick="javascript: alertName()">Click</a>
	 */
	function alertName(){
		$jx.ajax({
			url:ajaxurl,
			type:'POST',
			data:'action=pgst_ajax&name=myname',
			success:function(result){
				alert(result)
			}
		});
		return false;
	}

</script>
<?php
} //end myAjax2()

Then add these functions to wordpress:
If you want to do the ajax on the front page, add the ff:

add_action('wp_head','myAjax2');

If you want to do the ajax on the admin page, add the ff:

add_action('admin_head','myAjax2');
add_action('wp_ajax_pgst_ajax', 'myAjax1');
add_action('wp_ajax_nopriv_pgst_ajax', 'myAjax1');//for users that are not logged in
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *