Web Dev Tuts

/ Stuffs About Website Development /

Menu
  • Home
  • Wp Plugins
  • How To
  • FAQ
    • GIT
    • JQuery
    • PHP
    • WooCommerce
    • WordPress
  • Contact Us
Menu

Implementing Ajax in WordPress Themes and Plugins

Posted on June 8, 2012September 24, 2017 by admin

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
Category: Wordpress

Leave a Reply Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to add wp_editor Dynamically
  • How to Hide Certain Pages from Certain Users (WP Dashboard)
  • How to Set Up Gmail SMTP
  • How to Set Up Virtual Host in Localhost & Xampp
  • How to Determine the Current WordPress Version Used
  • AngularJs
  • CSS
  • For Me Only
  • geo location api
  • GIT
  • GoDaddy
  • Hosting
  • How To
  • Javascript
  • JQuery
  • Magento
  • My Notes
  • PHP
  • Private
  • Sass
  • WooCommerce
  • Wordpress
  • Xampp
© 2023 Web Dev Tuts | Powered by Minimalist Blog WordPress Theme