I have written a plugin which collects stats on document ready.
Keep in mind that my database table is already created.
I've added the following code to do the ajax code
add_action( 'wp_head', 'zkr_stats_ajax' );
function zkr_stats_ajax(){
?>
<script type='text/javascript' >
jQuery(document).ready(function() {
//jQuery(window).load(function() {
//set data varialbel with values
var data = {
action: 'action_stats',
zkr_filename: '<?php echo $_SERVER['PHP_SELF']; ?>',
zkr_ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>',
zkr_referer: '<?php if(isset($_SERVER['HTTP_REFERER'])){ echo $_SERVER['HTTP_REFERER'];}else{ } ?>',
zkr_browser: '<?php echo $_SERVER['HTTP_USER_AGENT']; ?>',
zkr_method: '<?php echo $_SERVER['REQUEST_METHOD']; ?>'
};
var ajaxurl = '<?php admin_url('admin-ajax.php'); ?>'; // set the admin ajax url
jQuery.post(ajaxurl, data, function(response) {
});
});
</script>
<?php
}
Then there is a function that handles the data being sent from the ajax above and stores the data into the mysql database table.
add_action('wp_ajax_nopriv_action_stats', 'zkr_stats_update'); //ajax callback
function zkr_stats_update(){
global $wpdb;
if(isset($_POST)){
$filename = $_POST['zkr_filename'];
$ip = $_POST['zkr_ip'];
$referer = $_POST['zkr_referer'];
$browser = $_POST['zkr_browser'];
$method = $_POST['zkr_method'];
$table_name = $wpdb->prefix . "zkr_stats";
$row = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE ip = '$ip' ");
if($wpdb->num_rows == 0){
$num = 1;
$wpdb->query( $wpdb->prepare( "INSERT INTO ". $wpdb->prefix ."zkr_stats(ip, filename, referer, browser, method, timestamp, number) VALUES('".$ip."', '".$filename."', '".$referer."', '".$browser."', '".$method."', NOW(), '".$num."')" )) or wp_die( 'Could not save data!' ); //insert new data if the current ip was not used before
}
elseif($wpdb->num_rows == 1){
foreach($row as $rows){
$num = $rows->number + 1;
}
$wpdb->query( $wpdb->prepare( "UPDATE ".$table_name." SET number = '".$num."' WHERE ip = '".$ip."'" ))or wp_die( 'Could not update data!' ); //update visit data for old ip
}
}
}
Now when the page loads, I can see in firebug that data is being posted via ajax, but nothing is getting saved.
Only when I add the function zkr_stats_update() to the header of the theme does it save but then it saves double, one empty and one with data.
What am I doing wrong?
Thanks guys

exit;as the last line ofzkr_stats_update()fix anything? – m0r7if3r Jan 31 '12 at 13:53$wpdb->prepare(...) ) } }, before the final}...and it shouldn't stop anything from executing unless you are using the same function to handle things which are not ajax calls. – m0r7if3r Jan 31 '12 at 14:07