Deleting WordPress posts in front-end with AJAX - javascript

I am trying to remove WordPress posts from front end using AJAX.
My code removes post, but displays blank page with "success", when i want to just fade out this post without page reloading and displaying blank page.
PHP code:
<?php if( current_user_can( 'delete_post' ) ) : ?>
<?php $nonce = wp_create_nonce('my_delete_post_nonce') ?>
delete
<?php endif ?>
Functions.php code:
function my_frontend_script() {
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_frontend_script' );
wp_localize_script( 'js/my_script.js', 'MyAjax2', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'ajaxnonce' => wp_create_nonce('ajax-nonce') ) );
add_action( 'wp_ajax_my_delete_post', 'my_delete_post' );
function my_delete_post(){
$permission = check_ajax_referer( 'my_delete_post_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
}
else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
my_script.js code:
jQuery( document ).ready( function($) {
$(document).on( 'click', '.delete-post', function() {
var id = $(this).data('id');
var nonce = $(this).data('nonce');
var post = $(this).parents('.post:first');
$.ajax({
type: 'post',
url: MyAjax2.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: id
},
success: function( result ) {
if( result == 'success7' ) {
post.fadeOut( function(){
post.remove();
});
}
}
})
return false;
})
})
The problem is page is reloading to a blank page with "success" text, when it should just fade out and remove post from current page, without reloading.
It looks like my_script.js is not even used at all :(
Any help much appreciated.

delete
it's reloading because it loads first the url in your href attribute, then executing your ajax-call. thats not what you want. you want to execute only the onclick. this should solve the problem. just put a # in your href
delete
or make buttons
<button data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</button>
edit: if it's still not working, it's because you got a typo here
if( result == 'success7' )
success7 instead of success

Related

WordPress admin-ajax returns bad request 400

In a template file, I need to get the new data from the frontend when a user double-clicks and changes the record on a table. I tested and the console shows that the request is correct, however whatever I tried the admin-Ajax returns always Bad Request!
The PHP code waiting for the request in the template file is:
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_please_login", "please_login" );
function update_records(){
global $wpdb;
$colName = "'" . $_POST['upd_column'] . "'";
$wpdb->update('Reservations',
array(
$colName => $_POST['upd_value']
),
array( 'ReservationID' => $_POST['record_id'] )
);
wp_die();
};
function please_login() {
echo "You must log in to work";
die();
}
The jQuery code sending the request is:
jQuery('#work td').dblclick(
function dolly_script() {
var text = jQuery(this).text();
var headerName = jQuery(this).attr('headers');
jQuery(this).text('');
jQuery('<input />').appendTo(jQuery(this)).val(text).select().blur(
function() {
var newVal = jQuery(this).val();
var selectionID = jQuery(this).closest("tr").children("td[headers='ReservationID']").text();
jQuery(this).parent().text(newVal).find('input').remove();
jQuery.ajax({
url: '../wp-admin/admin-ajax.php',
type: 'POST',
dataType : "json",
data: JSON.stringify({
action: 'update_records',
record_id: selectionID,
upd_column: headerName,
upd_value: newVal
})
})
})
});
I tried also without JSON.stringify and without datatype.
In functions file I have also added:
wp_register_script( 'dolly_script', '/wp-content/themes/bootcms/work.js');
$myAjax = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'dolly_script', 'ajax_url', $myAjax );
wp_enqueue_script( 'dolly_script' );
Inside the "add_action( 'wp_enqueue_scripts', 'myfunction' );" declaration.
If anyone could help is hugely appreciated, I spent a whole day but I found no solution.
I solved the problem. Here is the solution in case it helps others:
I moved the PHP function into the functions.php file.

PHP variables resetting after passing javascript variables through AJAX post

I'm trying to make some SQL queries using PHP in Wordpress, to auto populate and check values on a gravity form against the existing database.
To do that however, I'm going to need to pass some javascript variables to php, then use that to interact and pull that data back to the form. As someone with minimal web dev background, easier said then done.
My main issue is with an AJAX call that properly carries over a value, but only to the action function. All other calls will show null (I assume due to scoping, but globals don't seem to help).
The main relevant PHP is in a custom plugin as follows:
$address = 0;
function my_enqueue() {
wp_register_script( 'lead-scheduler', null);
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_register_script( 'lead_ajax', null);
wp_enqueue_script( 'lead_ajax' );
}
add_action( 'init', 'my_enqueue' );
function handle_request(){
//Check post address, then apply to global variable
echo $_POST['address'] . "\n";
global $address;
$address = $_POST['address'];
echo $address . "\n";
wp_die("RIP");
}
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var temp;
//Set up event listener
addressField.onchange = addressCheck;
function addressCheck(){
//Get foreign script
$.getScript("/wp-content/plugins/lead-scheduler/lead_ajax.js", function(){
//Wait until done to execute console.log
$.when(adrCheck()).done(function(){
console.log("Logging: " + "<?php global $address; echo $address ?>");
});
});
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller'); ?>
The AJAX call comes from a JS file that I call to:
//AJAX
function adrCheck(){
jQuery(document).ready( function() {
console.log("called")
var addressField = document.getElementById('input_22_2').value;
jQuery.ajax({
type : "post",
url : leadajax.ajax_url,
data : {action: "handle_request", address: addressField},
success: function(response) {
console.log(response)
},error: function(response){
console.log(response);
}
})
})
}
The call seems to work, as the echo in handle_request() works fine. But calling that variable anywhere else returns null. $.when.done doesn't seem to do much, nor does anything synchronous.
I'm sure there's something super elementary that I'm missing, but I can't seem to find it.

WooCommerce Ajax Cart Update Stopped Working

I found a function to automatically update the cart when the quantity of an item is changed, and it was working until WooCommerce's 3.2.0 updated (latest update 3.2.1). I'm pretty sure something changed within this code:
add_action('woocommerce_cart_updated', 'wac_update');
function wac_update() {
// is_wac_ajax: flag defined on wooajaxcart.js
if ( !empty($_POST['is_wac_ajax'])) {
$resp = array();
$resp['update_label'] = __( 'Update Cart', 'woocommerce' );
$resp['price'] = 0;
// render the cart totals (cart-totals.php)
ob_start();
do_action( 'woocommerce_after_cart_table' );
do_action( 'woocommerce_cart_collaterals' );
do_action( 'woocommerce_after_cart' );
$resp['html'] = ob_get_clean();
// calculate the item price
if ( !empty($_POST['cart_item_key']) ) {
$items = WC()->cart->get_cart();
$cart_item_key = $_POST['cart_item_key'];
if ( array_key_exists($cart_item_key, $items)) {
$cart_item = $items[$cart_item_key];
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$price = apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
$resp['price'] = $price;
}
}
echo json_encode($resp);
exit;
}
}
My Javascript still working but here it is for a reference:
function refreshCart() {
jQuery('.cart-builder .qty').on('change', function(){
var form = jQuery(this).closest('form');
// emulates button Update cart click
jQuery("<input type='hidden' name='update_cart' id='update_cart' value='1'>").appendTo(form);
// plugin flag
jQuery("<input type='hidden' name='is_wac_ajax' id='is_wac_ajax' value='1'>").appendTo(form);
var el_qty = jQuery(this);
var matches = jQuery(this).attr('name').match(/cart\[(\w+)\]/);
var cart_item_key = matches[1];
form.append( jQuery("<input type='hidden' name='cart_item_key' id='cart_item_key'>").val(cart_item_key) );
// get the form data before disable button...
var formData = form.serialize();
jQuery("input[name='update_cart']").val('Updating...').prop('disabled', true);
jQuery.post( form.attr('action'), formData, function(resp) {
// ajax response
jQuery('.cart-collaterals').html(resp.html);
el_qty.closest('.cart_item').find('.product-subtotal').html(resp.price);
console.log(resp.test);
jQuery('#update_cart').remove();
jQuery('#is_wac_ajax').remove();
jQuery('#cart_item_key').remove();
jQuery("input[name='update_cart']").val(resp.update_label).prop('disabled', false);
},
'json'
);
});
}
I've been looking through the change log, https://github.com/woocommerce/woocommerce/blob/master/CHANGELOG.txt, but I can't find what would be conflicting now. Like I said, it was working perfectly before this updated.
Ok here is a simpler solution, I am just appending a script to the bottom of the cart page but you could also enqueue it with wp_enqueue_script function which is the best way. All it does it simulates the pressing of the update cart button.
function cart_update_qty_script() {
if (is_cart()) :
?>
<script type="text/javascript">
(function($){
$(function(){
$('div.woocommerce').on( 'change', '.qty', function(){
$("[name='update_cart']").trigger('click');
});
});
})(jQuery);
</script>
<?php
endif;
}
add_action( 'wp_footer', 'cart_update_qty_script' );

How to call ajax in Wordpress

My ajax call output is always showing 0 as output don't know why
In functions.php I have this code
function get_data() {
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And my ajax call is in a javascript
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "GET",
dataType : "json",
url : "/wp-admin/admin-ajax.php",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.
In backend there is global ajaxurl variable defined by WordPress itself.
This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.
Good way to do this is to use wp_localize_script.
Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});
Actually, WordPress comes with a handy function to access admin-ajax.
Requirements
In wp-admin you do not need to do anything, the js library is always loaded
In the front-end you need to enqueue the script wp-util, like this:
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
function my_enqueue_function() {
// Option 1: Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
// Option 2: Make wp-util a dependency of your script (usually better).
wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
}
The JS Library
The wp-util script contains the wp.ajax object that you can use to make ajax requests:
wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
Your example:
wp.ajax.post( "get_data", {} )
.done(function(response) {
alert("Your vote could not be added");
alert(response);
});
PHP code
Of course, you still need to create the wp_ajax_* hooks in your PHP script.
add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
function my_ajax_handler() {
wp_send_json_success( 'It works' );
}
Tip:
For Ajax responses WordPress provides two functions:
wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)
I had the same problem. I was new to WordPress. Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.
First, create a function in function.php file that resides under wp-content/theme/selected_theme folder. Here, selected_theme maybe your theme name.
In the above question, a function is created with the name get_data();
function get_data() {
echo "test";
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
in the above two lines,
The add_action method is used to implement the hook. Here, I am passing the two parameters, first is wp_ajax_nopriv_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
In the second add_action, I am passing the two parameters, first is wp_ajax_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.
jQuery.ajax({
type: "post",
dataType: "json",
url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
data: {
action:'get_data', //this value is first parameter of add_action
id: 4
},
success: function(msg){
console.log(msg);
}
});
Add admin-ajax.php by using admin_url('admin-ajax.php');
<script type="text/javascript">
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "POST",
dataType : "json",
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
</script>
<form type="post" action="" id="newCustomerForm">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email">Email:</label>
<input name="email" type="text" />
<label for="phone">Phone:</label>
<input name="phone" type="text" />
<label for="address">Address:</label>
<input name="address" type="text" />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>
functions.php
wp_enqueue_script('jquery');
function addCustomer() {
global $wpdb;
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if ( $wpdb->insert( 'customers', array(
'name' => $name,
'email' => $email,
'address' => $address,
'phone' => $phone
) ) === false ) {
echo 'Error';
} else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
javascript
<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success: function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
If you are getting 0 in the response, it means your ajax call is working correctly.
But, you have not defined $wpdb as a global variable in your function get_data.
Check your error log, you must be seeing error there.
Try:
function get_data() {
global $wpdb;
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
Step 1: Add ajax 'wp_enqueue_script' file in function file where you have to add other 'wp_enqueue_script' or 'wp_enqueue_style' files
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax- script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Step 2:Now you need to create function, where you want to get response, using ajax
e.g below
add_action('wp_footer','add_ajaxex_in_footer');
function add_ajaxex_in_footer()
{ ?>
<script type="text/javascript">
jQuery('#sbmtbtn').click(function(){
jQuery.ajax({
type:"POST",
url:my_ajax_object.ajax_url,
data: {action:'my_special_ajax_call_enroll_cours'},
success:function(res){
console.log(res);
}
});
});</script><?php
}
Step 3: Now you have to create function where you have to write query,
add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');
function enroll_cours()
{
echo "Here you van write Query or anything";
exit;
}
=> If you want to fire ajax request after onClick button, just pass the button ID
<input type="button" id="sbmtbtn" name="Save">
Here how to make in plain vanilla js the AJAX call in WordPress.
var urlToajax=jsajaxe_S.ajaxurl;
function P_lifg(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
}
};
xmlhttp.open("GET", urlToajax+ "?action=testfirst", true);
xmlhttp.send(0);
}
See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action
Here add_actions in functions.php:
add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');
Add this function over that, here now this function:
function FunctionTF(){
exit( "Hola hola" );
}
See explanation why? code in "exit" in my blog
Here add this html on some wp-template
<div id="demo"></div>
<div id="demo2"></div>
<button id="spesial_button" onclick="P_lifg()">I am spesial</button>
See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html

How to disable link after first click and allow user to vote only if logged in

i am working on a plugin in wordpress to vote up a post or vote down using ajax.
Everything is working fine but the problem is am not able to disable the onclick eventhandler after first click so whenever someone voting a post , he can add vote multiple times. I want to ignore that so i should be able to vote only once. If i click on vote up then the voteup anchor tag should be disable and votedown anchor tag should be enable. At the same time if i click on the votedown anchor tag then votedown should be disable and voteup should be enable. Also i want to enable the voting feature only if the user is logged in the wordrpess.
I have a function to show a popup if the user is not logged in.
i.e login_open();
If user is not logged in and try to vote up then this function should execute login_open();
Otherwise user should be able to vote or downvote only once ..
Here is my code //
php
//Defining Base Paths
define('VOTEUPURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
define('VOTEUPPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );
//Enqueue Script for the Admin Ajax and Cutom Js File
function voteme_enqueuescripts()
{
wp_enqueue_script('voteme', VOTEUPURL.'/js/voteup.js', array('jquery'));
wp_localize_script( 'voteme', 'votemeajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_localize_script( 'votedown', 'votedownajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', voteme_enqueuescripts);
//Adding Vote up links to all the posts.
function voteme_getvotelink(){
$votemelink = "";
$post_ID = get_the_ID();
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$link = $votemecount.' '.'Vote Up'.'';
$link .=' '.'Vote Down'.'';
$votemelink = '<div id="voteme-'.$post_ID.'">';
$votemelink .= '<span>'.$link.'</span>';
$votemelink .= '</div>';
return $votemelink;
}
//Function to get the count
function get_current_vote_count(){
$voteup_count = "";
$post_ID = get_the_ID();
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votelink = '<span class="vote_count">'. $votemecount .'</span>';
return $votelink;
die($votelink);
}
//Add Vote Function
function voteme_addvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount + 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.=$votemecountNew;
// Return the String
die($results);
}
// creating Ajax call of ADD VOTE for WordPress
add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' );
add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );
//Add Vote Function
function voteme_downvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount - 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.= $votemecountNew;
// Return the String
die($results);
}
// creating Ajax call of DOWN VOTE for WordPress
add_action( 'wp_ajax_nopriv_voteme_downvote', 'voteme_downvote' );
add_action( 'wp_ajax_voteme_downvote', 'voteme_downvote' );
//Javascript and Ajax Calls
function votemeaddvote(postId)
{
jQuery.ajax({
type: 'POST',
url: votemeajax.ajaxurl,
data: {
action: 'voteme_addvote',
postid: postId
},
success:function(data, textStatus, XMLHttpRequest){
var vote_count_id = jQuery('.vote_count');
jQuery(vote_count_id).html('');
jQuery('.vote_count').append(data);
var thisr = jQuery('.voter button:first-child')
thisr.disable = true;
// add any additional logic here
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
}
function votemedownvote(postId)
{
jQuery.ajax({
type: 'POST',
url: votemeajax.ajaxurl,
data: {
action: 'voteme_downvote',
postid: postId
},
success:function(data, textStatus, XMLHttpRequest){
var vote_count_id = jQuery('.vote_count');
jQuery(vote_count_id).html('');
jQuery('.vote_count').append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
}
//HTML For Adding Votes
<div class="voter">
<a onclick="votemeaddvote(<?php echo $post_ID; ?>);">VoteUp</a>
<a onclick="votemedownvote(<?php echo $post_ID; ?>)">Vote Down</a>
</div>
Simplely using .one() instead of .on()
Try something like this,
$(".voter a:last-child").one( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemedownvote(data.id);
});
So what you could do is change some of your code
Change the html to this:
<div class="voter">
<a data-id="<?php echo $post_ID; ?>">VoteUp</a>
<a data-id="<?php echo $post_ID; ?>">Vote Down</a>
</div>
And change your javascript like this since you are using jquery:
$(".voter a").on( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemeupvote(data.id);
$(this).off();
});
So var data get has the post id in json form to be sent.
Using "this" you are able to target this specific element and turn its on click off. I removed your on embedded click events because usually you want to bootstrap those triggers so you can turn them off, which was your problem.
You can do this by using jquery .on and .off methods.
Edit: Forgot to add your function call. I added it. I will also add how your votedown can work:
$(".voter a:last-child").on( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemedownvote(data.id);
$(this).off();
});
Edit 2: Oh and I forgot to mention that this is only good for the front end. So in the backend you need someway to track if the person voted or not, maybe a table with user id, post id and voted true or false. That way you can track it when the ajax call comes and have php update the database.
Fiddle

Categories

Resources