0
我正在爲我的網站製作一種投票系統插件。當用戶點擊'like'按鈕時,jQuery ajax應該將該點擊發送給我的functions.php
中的一個函數,我稱其爲vote_funct
。 jQuery ajax腳本正在返回成功消息,但該函數根本不被調用。我不明白我做錯了什麼。下面是我的jQuery Ajax代碼:jQuery Ajax函數不能在Wordpress中工作
(function($){ //wordpress jquery no conflict starts here
$(document).ready(function($) {
var counter;
var id;
var ajaxurl = MyAjax.ajax_url;
$('.fa-plus').click(function(){
counter = 0;
id = $(this).closest('div').prop("id");
counter = counter+1;
$(this).css('color','green');
$(this).removeClass('fa fa-plus');
$(this).addClass('fa fa-check');
$.ajax({
url : ajaxurl,
type : "POST",
data : {
'action' : 'vote_funct',
'counter': counter,
'id' : id
},
success:function(data){
console.log("counter");
}
}).error(function(xhr, status){
switch(status){
case 404:
alert("404 not found");
break;
case 500:
alert("500 server error");
break;
case 0:
alert("0 request aborted");
break;
default:
alert("unknown " + ajaxurl);
}
});
}) ;
});
})(jQuery);
然後我vote_funct
這是位於functions.php的
$myfile = fopen("data.txt", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($_POST));
function vote_funct(){
$id = $_POST['id'];
$votes = $_POST['counter'];
if(!empty($_POST)){
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE fwwp_votes SET votes = votes +1 WHERE id = $id"));
}
echo true;
die();
}
add_action('wp_ajax_nopriv_vote_funct', 'vote_funct');
add_action('wp_ajax_vote_funct', 'vote_funct');
僅供參考data.txt
被寫入所有的數據正確。