Include ajax in wordpress using jquery?

To include ajax in wordpress plugin:-

for eg. if we want to use ajax on click of some event

<div id=”ajaxid” onclick=”testfn(1)” />

<script type=”text/javascript”>

function testfn(val) {

jQuery.ajax({
type: “post”,url: “admin-ajax.php”,data: { action: ‘save_data’, val: val},
success: function(html){ //so, if data is retrieved, store it in html
$(‘#id’ ).html(html);

});

}

</script>

here we are calling ajax using jquery.We have used three parameters

type:post

url :admin-ajax.php                It will remain fixed for plugins but if we want to use ajax in wordpress themes then this url will be different.That i’ll describe later on

in data we will give action name and also variables that we want to sent with ajax request.One thing is important here to register this function and we also need to include wp_ajax .

<?php

add_action( ‘wp_ajax_save_data’, ‘save_data_ajax’ );

function save_data_ajax'() {

$val = $_POST[‘val’];

echo ‘output’;

}

?>

To include ajax in wordpress theme:-

We need to include this hook in our functions.php

function give_do_action_for_ajax_call() {
/* Theme only, we already have the wp_ajax_ hook firing in wp-admin */
if ( !defined( ‘WP_ADMIN’ ) ) {
do_action( ‘wp_ajax_’ . $_REQUEST[‘action’] );
}
}
add_action( ‘init’, ‘give_do_action_for_ajax_call’ );

and url will be wp-load.php rest all will be same as i have described above.

jQuery.ajax({
		type: "post",url: "admin-ajax.php",data: { action: 'gethello3', count: count, _ajax_nonce: '<?php echo $nonce; ?>' },
		beforeSend: function() {jQuery("#helloworld").fadeOut('fast');}, //fadeIn loading just when link is clicked
		success: function(html){ //so, if data is retrieved, store it in html
			jQuery("#helloworld").html(html); //fadeIn the html inside helloworld div
			jQuery("#helloworld").fadeIn("fast"); //animation
		}
Advertisements

About Kapil Chugh

In love with PHP and tweaking WordPress. Hungry for Open Source and new technologies. Honest. God-fearing. Happiest when solving problems.
This entry was posted in jquery, WordPress and tagged , , . Bookmark the permalink.

One Response to Include ajax in wordpress using jquery?

  1. I’ve been browsing online more than three hours lately, yet I never found any fascinating article like yours. It is pretty worth sufficient for me. Personally, if all web owners and bloggers made excellent content as you probably did, the internet can be a lot more helpful than ever before.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s