Commit abed3e03 authored by Vadim's avatar Vadim

Version 2.7.1

Замена XMLHttpRequest на jQuery.ajax
parent c613fefb
......@@ -3,7 +3,7 @@
Plugin Name: Bg Az-Counter
Plugin URI: https://bogaiskov.ru
Description: Подсчет количества посещений страниц на базе stat.azbyka.ru
Version: 2.7
Version: 2.7.1
Author: VBog
Author URI: https://bogaiskov.ru
License: GPL2
......@@ -38,7 +38,7 @@
if ( !defined('ABSPATH') ) {
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_STAT_COUNTERS','https://stat.azbyka.ru/counters');
......
......@@ -112,7 +112,6 @@ jQuery( document ).ready(function() {
/*********************************************************************************
POST /counters/<path>
Увеличивает счётчик на единицу (и создаёт его, если он не существует).
Тело запроса пустое.
......@@ -135,33 +134,22 @@ jQuery( document ).ready(function() {
function SendOnce(type, id) {
var request = bg_counter.counterurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("POST", request, true);
if (bg_counter.debug) console.log('POST REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
// Здесь надо будет добавить вывод данных на экран
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!');
jQuery.ajax ({
url: request,
type: "POST",
success: function(response){
// Здесь надо будет добавить вывод данных на экран
if (bg_counter.debug) {
console.log('POST REQUEST: '+request+' result:');
console.log(JSON.stringify(response.data));
}
} 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);
}
}
xhr.send();
});
}
/*********************************************************************************
......@@ -243,15 +231,16 @@ function fullBatchQuery(socket) {
if( typeof elem == 'undefined' ) return false; // Нет полей для вывода информации на странице
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 = new Array();
var i = 0;
var elem_num = 0;
// Для каждого счетчика
elem.each (function () {
var el = jQuery(this);
var project = el.attr('data-project');
if (project == "") path = "/";
if (project == "") path = "/"; // Формируем путь
else {
if (project == undefined) project = bg_counter.project;
else project = '/project/'+project;
......@@ -260,16 +249,16 @@ function fullBatchQuery(socket) {
if (!type || !id) var path = project;
else var path = project+"/"+type+"/"+id;
}
if (elem_num >= bg_counter_elements) {
data_added[i] = path; //*************
if (elem_num >= bg_counter_elements) { // Только новые данные
data_added[i] = path;
i++;
}
data[elem_num] = path;
data[elem_num] = path; // Все данные
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 json_added = JSON.stringify(data_added);
var json = JSON.stringify(data);
......@@ -278,54 +267,53 @@ function fullBatchQuery(socket) {
console.log(" Path ("+i+"): "+json);
}
// Пакетный запрос
var xhr = new XMLHttpRequest();
xhr.open("POST", request, true);
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (bg_counter.debug) console.log('POST REQUEST: '+request+' result:');
if (bg_counter.debug) console.log(JSON.stringify(response));
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!');
// Пакетный запрос batch-query
jQuery.ajax ({
url: request,
type: "POST",
data: json_added,
success: function(data){
// Здесь надо будет добавить вывод данных на экран
if (bg_counter.debug) {
console.log('POST REQUEST: '+request+' result:');
console.log(JSON.stringify(data));
}
} 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);
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) {
......
......@@ -82,43 +82,39 @@ GET /item-score/project/test/author/1
function getRate(type, id) {
var request = bg_counter.scoreurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("GET", request, true);
if (bg_counter.debug) console.log('GET REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
// Вывод данных на экран
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);
}
jQuery.ajax ({
url: request,
type: "GET",
success: function(response){
if (bg_counter.debug) {
console.log('POST REQUEST: '+request+' result:');
console.log(JSON.stringify(response));
}
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>
......@@ -146,35 +142,32 @@ POST /rate/project/test/author/1/book/3
function sendRate(type, id, number) {
var request = bg_counter.rateurl+bg_counter.project+"/"+type+"/"+id;
var xhr = new XMLHttpRequest();
xhr.open("POST", request, true);
if (bg_counter.debug) console.log('POST REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
// Вывод данных на экран
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);
}
jQuery.ajax ({
url: request,
type: "POST",
success: function(response){
// Вывод данных на экран
if (bg_counter.debug) {
console.log('POST REQUEST: '+request+' result:');
console.log(JSON.stringify(response));
}
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