Ajax in WordPress

Hi PHP Developers ,

We know how to use jQuery Ajax in php , And using the same in WordPress has some little changes as WordPress has a Build in Ajax function using that only Ajax will work in WordPress.

WordPress Built in Ajax is

admin-ajax.php

So you need to include this files in your theme to make use to Ajax

And in the my_voter_script.js i can write any ajax functions and pass data to our frontend pages as needed,

jQuery(document).ready( function() {
var pid = val;
jQuery.ajax({
type : “post”,
url: “/wp-admin/admin-ajax.php”,
data : {action: “my_user_vote”, post_id : pid},
success: function(result) {
$(“#page1”).html(result);
}
});
});

Here in WordPress Ajax you find something like “action” inside data which is nothing but the data manipulation function , in normal php we call some php files and we do some data manipulation inside it and echo some results , like wise here it can be done through a function and from there you can pass the data

Use the below function in functions.php , As it is our building block for all functions

add_action(“wp_ajax_my_user_vote”, “my_user_vote”);
add_action(“wp_ajax_nopriv_my_user_vote”, “my_user_vote”);

function my_user_vote() {

$id = $_REQUEST[‘post_id’];

$loop = new WP_Query( array(‘post_type’ => ‘artistcontent’,’p’=>$id) );

while ( $loop->have_posts() ) : $loop->the_post();

the_title();

the_content();

the_post_thumbnail();

endwhile;

wp_reset_postdata();

wp_die();
}

wp_ajax hook is used to perform the action scripts

wp_ajax_prev is nothing the same hook which works for nonlogged in users.

 

 

 

Advertisements

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