Commit abed3e03 authored by Vadim's avatar Vadim

Version 2.7.1

Замена XMLHttpRequest на jQuery.ajax
parent c613fefb
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
Plugin Name: Bg Az-Counter Plugin Name: Bg Az-Counter
Plugin URI: https://bogaiskov.ru Plugin URI: https://bogaiskov.ru
Description: Подсчет количества посещений страниц на базе stat.azbyka.ru Description: Подсчет количества посещений страниц на базе stat.azbyka.ru
Version: 2.7 Version: 2.7.1
Author: VBog Author: VBog
Author URI: https://bogaiskov.ru Author URI: https://bogaiskov.ru
License: GPL2 License: GPL2
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
if ( !defined('ABSPATH') ) { if ( !defined('ABSPATH') ) {
die( 'Sorry, you are not allowed to access this page directly.' ); die( 'Sorry, you are not allowed to access this page directly.' );
} }
define('BG_COUNTER_VERSION', '2.7'); define('BG_COUNTER_VERSION', '2.7.1');
define('BG_COUNTER_LOG', dirname(__FILE__ ).'/bg_counter.log'); define('BG_COUNTER_LOG', dirname(__FILE__ ).'/bg_counter.log');
define('BG_COUNTER_STAT_COUNTERS','https://stat.azbyka.ru/counters'); define('BG_COUNTER_STAT_COUNTERS','https://stat.azbyka.ru/counters');
......
...@@ -112,7 +112,6 @@ jQuery( document ).ready(function() { ...@@ -112,7 +112,6 @@ jQuery( document ).ready(function() {
/********************************************************************************* /*********************************************************************************
POST /counters/<path> POST /counters/<path>
Увеличивает счётчик на единицу (и создаёт его, если он не существует). Увеличивает счётчик на единицу (и создаёт его, если он не существует).
Тело запроса пустое. Тело запроса пустое.
...@@ -135,33 +134,22 @@ jQuery( document ).ready(function() { ...@@ -135,33 +134,22 @@ jQuery( document ).ready(function() {
function SendOnce(type, id) { function SendOnce(type, id) {
var request = bg_counter.counterurl+bg_counter.project+"/"+type+"/"+id; var request = bg_counter.counterurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("POST", request, true); jQuery.ajax ({
if (bg_counter.debug) console.log('POST REQUEST: '+request); url: request,
xhr.onreadystatechange = function() { type: "POST",
if (xhr.readyState != 4) return; success: function(response){
if (xhr.status == 200) { // Здесь надо будет добавить вывод данных на экран
if (xhr.responseText) { if (bg_counter.debug) {
var response = JSON.parse(xhr.responseText); console.log('POST REQUEST: '+request+' result:');
if (response.success) { console.log(JSON.stringify(response.data));
// Здесь надо будет добавить вывод данных на экран
if (bg_counter.debug) {
console.log('POST REQUEST: '+request+' result:');
console.log(JSON.stringify(response.data));
}
setViewCount (type, id, bg_counter_number_format(response.data.value), addDelimiter(response.data.now+1));
} else {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR: '+response.error);
}
} else {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' Warning: responseText is empty!');
} }
} else { setViewCount (type, id, bg_counter_number_format(response.data.value), addDelimiter(response.data.now+1));
},
error: function(xhr) {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText); if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText);
} }
} });
xhr.send();
} }
/********************************************************************************* /*********************************************************************************
...@@ -243,15 +231,16 @@ function fullBatchQuery(socket) { ...@@ -243,15 +231,16 @@ function fullBatchQuery(socket) {
if( typeof elem == 'undefined' ) return false; // Нет полей для вывода информации на странице if( typeof elem == 'undefined' ) return false; // Нет полей для вывода информации на странице
if (notconnected > bg_counter.maxreconnect) return false; // Не более maxReConnect сбоев при запросе if (notconnected > bg_counter.maxreconnect) return false; // Не более maxReConnect сбоев при запросе
if (elem.length > bg_counter_elements) { if (elem.length > bg_counter_elements) { // Если количество счетчиков на странице больше уже учтенных
var data_added = new Array(); var data_added = new Array();
var data = new Array(); var data = new Array();
var i = 0; var i = 0;
var elem_num = 0; var elem_num = 0;
// Для каждого счетчика
elem.each (function () { elem.each (function () {
var el = jQuery(this); var el = jQuery(this);
var project = el.attr('data-project'); var project = el.attr('data-project');
if (project == "") path = "/"; if (project == "") path = "/"; // Формируем путь
else { else {
if (project == undefined) project = bg_counter.project; if (project == undefined) project = bg_counter.project;
else project = '/project/'+project; else project = '/project/'+project;
...@@ -260,16 +249,16 @@ function fullBatchQuery(socket) { ...@@ -260,16 +249,16 @@ function fullBatchQuery(socket) {
if (!type || !id) var path = project; if (!type || !id) var path = project;
else var path = project+"/"+type+"/"+id; else var path = project+"/"+type+"/"+id;
} }
if (elem_num >= bg_counter_elements) { if (elem_num >= bg_counter_elements) { // Только новые данные
data_added[i] = path; //************* data_added[i] = path;
i++; i++;
} }
data[elem_num] = path; data[elem_num] = path; // Все данные
elem_num++; elem_num++;
}); });
bg_counter_elements = elem.length; bg_counter_elements = elem.length; // Учитены все счетчики на страниц
if (data_added.length) { if (data_added.length) { // Если есть добавленые счетчики
var request = bg_counter.batch; var request = bg_counter.batch;
var json_added = JSON.stringify(data_added); var json_added = JSON.stringify(data_added);
var json = JSON.stringify(data); var json = JSON.stringify(data);
...@@ -278,54 +267,53 @@ function fullBatchQuery(socket) { ...@@ -278,54 +267,53 @@ function fullBatchQuery(socket) {
console.log(" Path ("+i+"): "+json); console.log(" Path ("+i+"): "+json);
} }
// Пакетный запрос // Пакетный запрос batch-query
var xhr = new XMLHttpRequest(); jQuery.ajax ({
xhr.open("POST", request, true); url: request,
xhr.onreadystatechange = function() { type: "POST",
if (xhr.readyState != 4) return; data: json_added,
if (xhr.status == 200) { success: function(data){
if (xhr.responseText) { // Здесь надо будет добавить вывод данных на экран
var response = JSON.parse(xhr.responseText); if (bg_counter.debug) {
if (bg_counter.debug) console.log('POST REQUEST: '+request+' result:'); console.log('POST REQUEST: '+request+' result:');
if (bg_counter.debug) console.log(JSON.stringify(response)); console.log(JSON.stringify(data));
jQuery('span.bg-az-counter').each (function () {
var el = jQuery(this);
var type = el.attr('data-type');
var id = el.attr('data-ID');
var project = el.attr('data-project');
if (project == "") path = "/";
else {
if (project == undefined) project = bg_counter.project.replace('/project/','/project:');
else project = '/project:'+project;
if (!type || !id) var path = project;
else var path = project+"/"+type+":"+id;
}
for (var key in response) {
if(path == key) {
if (response[key].viewCounter)
el.find('span.bg-az-counter-views').text(bg_counter_number_format(response[key].viewCounter));
else
el.find('span.bg-az-counter-views').text(0);
el.find('span.bg-az-counter-now').text(addDelimiter(response[key].onlineCounter));
if (response[key].rating)
el.find('span.bg-az-counter-score').text(parseFloat(response[key].rating.score).toFixed(1));
else
el.find('span.bg-az-counter-score').text('-');
}
}
});
} else {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' Warning: responseText is empty!');
} }
} else { // Для каждого счетчика
jQuery('span.bg-az-counter').each (function () {
var el = jQuery(this);
var type = el.attr('data-type');
var id = el.attr('data-ID');
var project = el.attr('data-project');
if (project == "") path = "/"; // Формируем путь
else {
if (project == undefined) project = bg_counter.project.replace('/project/','/project:');
else project = '/project:'+project;
if (!type || !id) var path = project;
else var path = project+"/"+type+":"+id;
}
for (var key in data) {
if(path == key) { // Сравниваем путь с ключем присланных данных
// Количество посещений
if (data[key].viewCounter)
el.find('span.bg-az-counter-views').text(bg_counter_number_format(data[key].viewCounter));
else
el.find('span.bg-az-counter-views').text(0);
// Количество online-посетителей
el.find('span.bg-az-counter-now').text(addDelimiter(data[key].onlineCounter));
// Райтинг
if (data[key].rating)
el.find('span.bg-az-counter-score').text(parseFloat(data[key].rating.score).toFixed(1));
else
el.find('span.bg-az-counter-score').text('-');
}
}
});
},
error: function(xhr) {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText); if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText);
notconnected++; notconnected++; // Количество повторов запросов
} }
} });
xhr.onerror = function(err) {
console.warn(err.type +" "+ err.target.status + ". Check if the server is running!");
}
xhr.send(json_added);
// Отправляем данные, как только сокет будет подключен // Отправляем данные, как только сокет будет подключен
if (socket.readyState == WebSocket.OPEN) { if (socket.readyState == WebSocket.OPEN) {
......
...@@ -82,43 +82,39 @@ GET /item-score/project/test/author/1 ...@@ -82,43 +82,39 @@ GET /item-score/project/test/author/1
function getRate(type, id) { function getRate(type, id) {
var request = bg_counter.scoreurl+bg_counter.project+"/"+type+"/"+id; var request = bg_counter.scoreurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("GET", request, true); jQuery.ajax ({
if (bg_counter.debug) console.log('GET REQUEST: '+request); url: request,
xhr.onreadystatechange = function() { type: "GET",
if (xhr.readyState == 4 && xhr.status == 200) { success: function(response){
if (xhr.responseText) { if (bg_counter.debug) {
var response = JSON.parse(xhr.responseText); console.log('POST REQUEST: '+request+' result:');
if (response.success) { console.log(JSON.stringify(response));
// Вывод данных на экран
if (bg_counter.debug) console.log(JSON.stringify(response.data));
m = response.data.votes % 10;
j = response.data.votes % 100;
if(m==0 || m>=5 || (j>=10 && j<=20)) txt_votes = bg_counter.votes5;
else if(m>=2 && m<=4) txt_votes = bg_counter.votes2;
else txt_votes = bg_counter.vote1;
start_rate_index = parseFloat(response.data.score).toFixed(1);
jQuery('#bg_counter_votes').html(response.data.votes);
jQuery('#bg_counter_votes_txt').html(txt_votes);
jQuery('#bg_counter_score').html(start_rate_index);
jQuery('meta[itemprop=ratingCount]').attr("content", response.data.votes);
jQuery('meta[itemprop=ratingValue]').attr("content", start_rate_index);
rating_voted = response.data.alreadyVoted;
iniRatingState(start_rate_index, rating_voted);
} else {
if (bg_counter.debug) console.log('GET REQUEST: '+request+' ERROR: '+response.error);
jQuery('#bg_counter_votes').html('0');
jQuery('#bg_counter_votes_txt').html(bg_counter.votes5);
jQuery('#bg_counter_score').html('0');
jQuery('meta[itemprop=ratingCount]').attr("content", 0);
jQuery('meta[itemprop=ratingValue]').attr("content", 0);
iniRatingState(0, false);
}
} }
m = response.data.votes % 10;
j = response.data.votes % 100;
if(m==0 || m>=5 || (j>=10 && j<=20)) txt_votes = bg_counter.votes5;
else if(m>=2 && m<=4) txt_votes = bg_counter.votes2;
else txt_votes = bg_counter.vote1;
start_rate_index = parseFloat(response.data.score).toFixed(1);
jQuery('#bg_counter_votes').html(response.data.votes);
jQuery('#bg_counter_votes_txt').html(txt_votes);
jQuery('#bg_counter_score').html(start_rate_index);
jQuery('meta[itemprop=ratingCount]').attr("content", response.data.votes);
jQuery('meta[itemprop=ratingValue]').attr("content", start_rate_index);
rating_voted = response.data.alreadyVoted;
iniRatingState(start_rate_index, rating_voted);
},
error: function(xhr) {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText);
jQuery('#bg_counter_votes').html('0');
jQuery('#bg_counter_votes_txt').html(bg_counter.votes5);
jQuery('#bg_counter_score').html('0');
jQuery('meta[itemprop=ratingCount]').attr("content", 0);
jQuery('meta[itemprop=ratingValue]').attr("content", 0);
iniRatingState(0, false);
} }
} });
xhr.send();
} }
/********************************************************************************* /*********************************************************************************
POST /rate/<path> POST /rate/<path>
...@@ -146,35 +142,32 @@ POST /rate/project/test/author/1/book/3 ...@@ -146,35 +142,32 @@ POST /rate/project/test/author/1/book/3
function sendRate(type, id, number) { function sendRate(type, id, number) {
var request = bg_counter.rateurl+bg_counter.project+"/"+type+"/"+id; var request = bg_counter.rateurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("POST", request, true); jQuery.ajax ({
if (bg_counter.debug) console.log('POST REQUEST: '+request); url: request,
xhr.onreadystatechange = function() { type: "POST",
if (xhr.readyState == 4 && xhr.status == 200) { success: function(response){
if (xhr.responseText) { // Вывод данных на экран
var response = JSON.parse(xhr.responseText); if (bg_counter.debug) {
if (response.success) { console.log('POST REQUEST: '+request+' result:');
// Вывод данных на экран console.log(JSON.stringify(response));
if (bg_counter.debug) console.log(JSON.stringify(response.data));
m = response.data.votes % 10;
j = response.data.votes % 100;
if(m==0 || m>=5 || (j>=10 && j<=20)) txt_votes = bg_counter.votes5;
else if(m>=2 && m<=4) txt_votes = bg_counter.votes2;
else txt_votes = bg_counter.vote1;
start_rate_index = parseFloat(response.data.score).toFixed(1);
jQuery('#bg_counter_votes').html(response.data.votes);
jQuery('#bg_counter_votes_txt').html(txt_votes);
jQuery('#bg_counter_score').html(start_rate_index);
jQuery('meta[itemprop=ratingCount]').attr("content", response.data.votes);
jQuery('meta[itemprop=ratingValue]').attr("content", start_rate_index);
iniRatingState(start_rate_index, true);
getAllRates();
} else {
if (bg_counter.debug) console.log('POST REQUEST: '+request+' ERROR: '+response.error);
}
} }
m = response.data.votes % 10;
j = response.data.votes % 100;
if(m==0 || m>=5 || (j>=10 && j<=20)) txt_votes = bg_counter.votes5;
else if(m>=2 && m<=4) txt_votes = bg_counter.votes2;
else txt_votes = bg_counter.vote1;
start_rate_index = parseFloat(response.data.score).toFixed(1);
jQuery('#bg_counter_votes').html(response.data.votes);
jQuery('#bg_counter_votes_txt').html(txt_votes);
jQuery('#bg_counter_score').html(start_rate_index);
jQuery('meta[itemprop=ratingCount]').attr("content", response.data.votes);
jQuery('meta[itemprop=ratingValue]').attr("content", start_rate_index);
iniRatingState(start_rate_index, true);
getAllRates();
},
error: function(xhr) {
if (bg_counter.debug) console.warn('POST REQUEST: '+request+' ERROR '+xhr.status+': '+xhr.statusText);
} }
} });
xhr.send('{"rating": '+number+'}');
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment