Reputation: 193
I have a vote functionality on my page, where the page visitor is supposed to click a button, then that click is saved in the database. Nothing is being saved in the database though: Here's the jQuery:
jQuery(document).ready(function(){
jQuery('.site-footer').hide();
var counter;
var id;
jQuery('.fa-plus').click(function(){
counter = 0;
id = jQuery(this).closest('div').prop("id");
counter = counter+1;
jQuery(this).css('color','green');
jQuery(this).parent().html(counter);
alert(name);
jQuery.ajax({
url : "<?php $_SERVER['PHP_SELF'] ?>",
type : "POST",
data : {
'action' : 'add_votes',
'counter': counter,
'id' : id,
},
success:function(response){
console.log(response);
}
});
});
});
and my WordPress insert statement:
add_action( 'wp_footer', 'my_action_javascript' );
function add_votes(){
$id = $_POST['id'];
$votes= $_POST['counter'];
if( !empty($_POST) ){
global $wpdb;
$wpdb->insert(
'fwwp_votes',
array(
'bride_id' => $id,
'votes' => $votes
),
array(
'%d',
'%d'
)
);
}
}
add_action( 'wp_ajax_no_priv_add_votes', 'add_votes' );
add_action( 'wp_ajax_add_votes', 'add_votes' );
Upvotes: 1
Views: 338
Reputation: 338
You provided the value for the url
is wrong.
Wordpress gives us a unified file to use – wp-admin/admin-ajax.php. In Wordpress you must always use it's own unified file admin_url( 'admin-ajax.php' )
to send request through AJAX.
Replace
url : "<?php $_SERVER['PHP_SELF'] ?>",
To
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
in $.ajax()
parameters
Upvotes: 1