AJAX Click Counter – How to Update WP Database?
-
Hi, I’m trying to write a plugin which will count clicks to the database for any link the following code is added to:
onclick="myCounter(<?php echo $post->ID ?>);"
I’ve read the Codex on AJAX in Plugins, as well as all other posts I could find about this online, but I just can’t seem to get it to work. Anyone familiar with AJAX use in WP, please let me know what I’m doing wrong. Here is my code so far…
In my plugin folder I have /js/Counter.js:
function myCounter(postid){ jQuery.post( MyAjax.ajaxURL,{ action:'myClickCounter', id:postid } ) };
In my plugin file /referrer-hits.php I have this:
// embed the javascript file that makes the AJAX request wp_enqueue_script( 'Counter', plugin_dir_url( __FILE__ ) . 'js/Counter.js', array( 'jquery' ) ); // declare the URL to the file that handles the AJAX request wp_localize_script( 'Counter', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); function myClickCounter() { global $wpdb; $post_id = $_POST['id']; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_value = meta_value+1 WHERE post_id = %d AND meta_key = 'outgoing_hits'", $post_id ) ) or die("Invalid query: " . mysql_error()); } add_action('wp_ajax_myClickCounter', 'myClickCounter' ); add_action('wp_ajax_nopriv_myClickCounter', 'myClickCounter' );
I’ve found several articles on how to pass a variable to a separate php file via POST with AJAX, but I can’t figure out how to pass it to my plugin code (if that makes sense). Any help appreciated on this!
[ Please don’t bump, that’s not permitted here. ]
- The topic ‘AJAX Click Counter – How to Update WP Database?’ is closed to new replies.