This is my first attempt at Ajax. I’ve got it working in the fact that the database gets the record inserted properly, however, once that’s done it won’t return the response that I’ve set up. Its as if AJAX isn’t being called at all. Any help would be greatly appreciated.
Here is my code:
//Enqueue Scripts
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "growwell_script", WP_PLUGIN_URL.'/growwell_activities/js/growwell_script.js', array('jquery') );
wp_localize_script( 'growwell_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'growwell_script' );
}
This part is in a content filter (but outputs as expected):
$link = admin_url('admin-ajax.php?action=gw_add_activity&wp_user_id='.$wp_user_id.'&activity_post_id='. $activity_post_id.'&nonce='.$nonce);
$content .= '<a href="'.$link.'" id="add-to-activity" wp_user_id="'. $wp_user_id .'" data-nonce="' . $nonce . ' activity_post_id="'. $activity_post_id .'" class="btn">Add to My Activities</a>';
My AJAX PHP:
add_action("wp_ajax_gw_add_activity", "gw_add_activity");
add_action("wp_ajax_nopriv_gw_add_activity", "my_must_login");
function gw_add_activity() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "gw_add_activity_nonce")) {
exit("No naughty business please");
}
$wp_user_id = $_REQUEST['wp_user_id'];
$activity_post_id = $_REQUEST['activity_post_id'];
$activity_added = current_time('mysql', 1);
global $wpdb;
$wpdb->insert(
'my_table',
array(
'wp_user_id' => $wp_user_id,
'activity_post_id' => $activity_post_id,
'date_added' => $activity_added,
'activity_status' => 'active'
)
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result_add = json_encode($result_add);
echo $result_add;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
exit();
}
function my_must_login() {
echo "You must be logged in to add to your activities.";
exit();
}
And Finally, my jQuery:
jQuery(document).ready( function() {
jQuery("#add-to-activity").click( function() {
nonce = jQuery(this).attr("data-nonce")
wp_user_id = jQuery(this).attr("wp_user_id")
activity_post_id = jQuery(this).attr("activity_post_id")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "gw_add_activity",
"wp_user_id" : wp_user_id,
"activity_post_id" : activity_post_id,
"nonce" : nonce
},
success: function(response) {
jQuery("#gw_feedback").html('It worked...' )
}
})
})
})