Ajax call in wordpress functions.php using jQuery


/* Paste below code in header.php or footer.php */

jQuery.ajax({
type: “POST”,
url: “<?php echo admin_url( ‘admin-ajax.php’ ); ?>”,
data:{
action: “my_action”,
“date”: date,
“month”: month,
“year”: year
},
}).success(function(result){
alert(result);
});

/* Paste below code in functions.php */

add_action( ‘wp_ajax_my_action’, ‘my_action_callback’ );
add_action( ‘wp_ajax_nopriv_my_action’, ‘my_action_callback’ );

function my_action_callback(){
global $wpdb;
$events = $wpdb->get_results(“SELECT ID, title FROM table_name”);
$data = “<ul>”;
foreach($events as $evt){
$data .= “<li>”;
$data .= ‘<a href=”#” target=”_blank”>’.$evt->title.'</a>’;
$data .= “</li>”;
}
$data .= “</ul>”;
echo $data; exit;
}

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