I've been browsing through similar questions and have yet to get this functionality to work. I'm tracking the progress a user makes an embedded vimeo video and insert data or update data.
JS on the post page:
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'vimeo_progress',
'progress_percent': progress,
'progress_seconds': seconds,
'course_id': courseID },
success : function(data) {
console.log(data); //FOR DEBUG
},
error : function(data, textStatus, XMLHttpRequest) {
console.log('updateProgress failed!'); //FOR DEBUG
console.log(textStatus); //FOR DEBUG
}
});
functions.php
add_action( 'wp_ajax_nopriv_vimeo_progress', 'store_vimeo_progress_callback' );
function store_vimeo_progress_callback() {
// don't track if user is not logged in
if ( ! is_user_logged_in() )
return false;
$user_id = get_current_user_id();
$vimeo_percent = sanitize_text_field($_POST['progress_percent']);
$vimeo_seconds = sanitize_text_field($_POST['progress_seconds']);
$xxx_course_id = sanitize_text_field($_POST['course_id']);
$table_name = $wpdb->prefix . "course_video_progress";
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $xxx_course_id) );
if ($row) {
$wpdb->replace(
$table_name,
array(
'id' => $row->id,
'user_id' => $user_id,
'course_id' => $xxx_course_id,
'progress_percent' => $vimeo_percent,
'seconds_played' => $vimeo_seconds
),
array(
'%d',
'%d',
'%f',
'%d'
)
);
} else {
$wpdb->insert(
$table_name,
array(
'user_id' => $user_id,
'course_id' => $xxx_course_id,
'progress_percent' => $vimeo_percent,
'seconds_played' => $vimeo_seconds
),
array(
'%d',
'%d',
'%f',
'%d'
)
);
}
$response = array( 'success' => true, 'data' => 'hello' ); //if $data is set
wp_send_json_success( $response );
exit;
}
No data is ever inserted into table and no data is ever updated. I do get a "success" from callback but the data is returned as 0.
edit: I just realized http://localhost/wordpress/wp-admin/admin-ajax.php returns 0 so maybe the ajax call is not even finding my function and simply returning 0?