基本上我有一个huuuuuge ajax / javascript / php脚本 (我知道它远远不是好的/优化的,但它就是它)
我正在制作一个评级脚本,但是当用户已经将数据库中的所有图像投票时,一个按钮将被添加到dom中,这样就可以通过评级图像“洗牌”......但是现在shuffle按钮通过调用具有固定值newImage(5,5,已检查);
的AJAX函数来工作(参见main.js中的shuffleRefresh())
但是这些值就像投票给id为“5”的图像并给它一个“5”作为评级....我该如何以更聪明的方式做到这一点?我这样做似乎很愚蠢......我能在这做什么?
的index.php
$dbCon = dbCon();
if (isset($_POST['submitTrun'])) {
$sql = "TRUNCATE TABLE rating_users";
$dbCon->query($sql);
$_POST['submitTrun'] = array();
}
$sql = "SELECT id, views, rating, votes FROM rating ORDER BY id DESC LIMIT 1";
$result = $dbCon->query($sql);
$result = $result->fetch_object();
$id = $result->id;
$votes = $result->votes;
$views = $result->views;
$rating = $result->rating;
$average = averageRate($rating, $votes);
//UPDATERE DATABASED
$stmt = $dbCon->prepare("UPDATE rating SET
views = views + 1 WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$sql = " SELECT user_ip, user_source, user_vote FROM rating_users WHERE user_ip = $ip AND user_source = $id";
$result = $dbCon->query($sql);
$result = $result->fetch_object();
$rating = $result->user_vote;
if (empty($result)) {
//BILLEDE + DENS VALUE
$imgRating .= "<img id=\"imgSrc\" src=\"assets/img/$id.jpg\" class=\"babeImg boxsb show\">";
$imgRating .= "<input id=\"imgValue\" class=\"absolute displayn\" type=\"radio\" value=\"$id\">";
$starRating = "";
for ($i = 5; $i > 0; $i--) {
$starRating .= "<input id=\"vote$i\" class=\"vote displayn\" type=\"radio\" name=\"vote\" value=\"$i\">";
$starRating .= "<label id=\"voteLabel$i\" class=\"voteHover\" for=\"vote$i\"></label>";
}
$starRating .= "<input type=\"submit\" id=\"voteSubmit\" class=\"displayn\">";
//STAR FORM END
$voteYesNo = "voteYes";
$voteText = "Du kan vote";
} else {
$sql = "SELECT user_vote FROM rating_users WHERE user_ip = $ip AND user_source = $id";
$result1 = $dbCon->query($sql);
$result1 = $result1->fetch_object();
$user_vote = $result1->user_vote;
$imgRating = "<img id=\"imgSrc\" src=\"assets/img/$id.jpg\" class=\"babeImg boxsb show\">";
$imgRating .= "<input id=\"imgValue\" class=\"absolute displayn\" type=\"radio\" value=\"$id\">";
$starRating;
for ($i = $user_vote; $i < 5; $i++) {
$starRating .= "<div class=\"voteEmpty\"></div>";
}
for ($i = 1; $i <= $user_vote; $i++) {
$starRating .= "<div class=\"voteFull\"></div>";
}
$shuffleImg = "<img id=\"shuffleImg\" class=\"shuffleImg\" src=\"assets/img/refresh.png\" alt=\"refresh\">";
$voteYesNo = "voteNo";
$voteText = "Du har votet";//VOTABLE
}
?>
<a href="index.php?page=contribuate" class="absolute top0 right0 zdeks1">Contribuate</a>
<div class="flex row100">
<div class="absolute left0 top0">
<form action="" method="post" class="absolute left0 top0 zdeks1">
<input id="submitTrun" type="submit" name="submitTrun">
</form>
</div>
<div class="col100 row100 bgc2 relative vh100 selectn flex-dc flex">
<div class="categoryWrapper relative flex center col100 padt20">
<input id="catBooty" class="kategorier " type="checkbox" checked="checked" value="1">
<label for="catBooty" class="pointer"><img src="assets/img/booty.png" alt="The Booty Way"></label>
<input id="catBooby" class="kategorier " type="checkbox" checked="checked" value="2">
<label for="catBooby" class="pointer"><img src="assets/img/booby.png" alt="The Booby Way"></label>
<input id="catPantsy" class="kategorier" type="checkbox" checked="checked" value="3">
<label for="catPantsy" class="pointer"><img src="assets/img/pantsy.png" alt="The Pantsy Way"></label>
</div>
<div id="globalRating2" class="globalRating2 col100 relative flex center flex1 overflowh">
<div id="globalRating" class="inlineb relative leftIn">
<div id="innerGlobalRating" class="innerGlobalRating flex bgc1">
<div id="imgInfoWrap" class="imgInfoWrap relative top0 left0 pad10 flex flex-dc">
<p id="imgViews" class="views alignic flex cursdef cw"><?php echo $views; ?></p>
<p id="imgVotes" class="votes alignic flex cursdef cw"><?php echo $votes; ?> </p>
<p id="imgAverage" class="average alignic flex cursdef cw"><?php echo $average; ?>/5</p>
<p id="votedYesNo" class="<?php echo $voteYesNo ?> alignic flex cursdef cw"><?php echo $voteText ?></p>
<div class="alignfe flex1 flex">
<p id="imgTime" class="imgTime alignic flex cursdef cw padt5">27/03/2017</p>
</div>
</div>
<div id="imgInnerWrap" class="relative flex bgc1">
<div id="imgInner" class="imgInner relative">
<div id="shuffleImgWrap" class="shuffleImgWrap absolute top0 right0 mar15">
<?php
if (isset($shuffleImg)) {
echo $shuffleImg;
}
?>
</div>
<?php
if (isset($imgRating)) {
echo $imgRating;
}
?>
</div>
<div id="starWrapper" class="starWrapper flex center flex-drr absolute col100 bot0">
<?php echo $starRating; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
main.js
function hasChild(parent, ids) {
return parent.querySelector(ids) !== null;
// var hasChild = parentDiv.querySelector("#child2") != null;
}
function hasClass(element, cls) {
return element.classList.contains(cls);
}
function createElement(type, attributes, someElement) {
var element = document.createElement(type);
for (var key in attributes) {
if (key === "class") {
var cls = attributes[key];
for (var c in cls)
element.classList.add(cls[c]);
} else {
element[key] = attributes[key];
}
}
someElement.appendChild(element);
}
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
let checked = "1,2,3";
for (let i = 0; i < kategorierLength; i++) {
kategorier[i].addEventListener('click', function () {
checked = '';
for (var k = 0; k < kategorierLength; k++) {
if (checked) {
var separator = ',';
} else {
var separator = '';
}
if (kategorier[k].checked) {
checked += separator + kategorier[k].value;
}
}
console.log(checked);
});
}
function starRating() {
var vote = document.getElementsByClassName('vote');
var voteL = vote.length;
for (let i = 0; i < voteL; i++) {
let voteValue = vote[i].value;
vote[i].addEventListener('click', function () {
var imgValue = document.getElementById("imgValue").value;
newImage(voteValue, imgValue, checked);
console.log(vote[i].value);
});
}
}
setTimeout(starRating, 500);
function shuffleRefresh() {
if (document.getElementById("shuffleImgWrap")) {
var shuffleImgWrap = document.getElementById("shuffleImgWrap");
shuffleImgWrap.addEventListener("click", function () {
if (document.getElementById("shuffleImg") !== null) {
var shuffleImg = document.getElementById("shuffleImg");
newImage(5, 5, checked);
}
});
}
}
shuffleRefresh();
function newImage(voteValue, imgValue, checked) {
if (checked === "") {
} else {
var imgSrc = document.getElementById('imgSrc');
var http = new XMLHttpRequest();
var url = "pages/newImage.php";
var params = "voteValue=" + voteValue + "&imgValue=" + imgValue + "&checked=" + checked;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
var globalRating2 = document.getElementById("globalRating2");
var globalRating = document.getElementById("globalRating");
var innerGlobalRating = document.getElementById("innerGlobalRating");
var imgValue = document.getElementById('imgValue');
console.log(this.responseText);
var jsonData = JSON.parse(this.responseText);
var content = jsonData.content;
if (jsonData.views) {
$views = jsonData.views;
}
if (jsonData.votes) {
$votes = jsonData.votes;
}
if (jsonData.average) {
$average = jsonData.average += "/5";
}
if (jsonData.imgSrc) {
var imgSrc = jsonData.imgSrc;
}
if (jsonData.id) {
var jsonId = jsonData.id;
}
//LEFT SLIDE START
if (hasClass(globalRating, "leftIn")) {
globalRating.classList.remove("leftIn");
globalRating.classList.add("leftOut");
}
setTimeout(newContent, 500);
function newContent() {
while (globalRating2.firstChild) {
globalRating2.removeChild(globalRating2.firstChild);
}
if (content === "newImg" || content === "ratedImg") {
var newElement = createElement("div", {
"id": "globalRating",
"class": ["inlineb", "relative", "leftIn"]
}, globalRating2);
var globalRating = document.getElementById("globalRating");
var newDiv = createElement("div", {
"id": "innerGlobalRating",
"class": ["innerGlobalRating", "flex", "bgc1", "boxsb"]
}, globalRating);
var innerGlobalRating = document.getElementById("innerGlobalRating");
var imgInfoWrap = document.getElementById("imgInfoWrap");
var newDiv = createElement("div", {
"id": "imgInfoWrap",
"class": ["imgInfoWrap", "relative", "top0", "left0", "pad10", "flex", "flex-dc"]
}, innerGlobalRating);
var imgInfoWrap = document.getElementById("imgInfoWrap");
var newParagraph = createElement("p", {
"id": "imgViews",
"class": ["views", "alignic", "flex", "cursdef", "cw"]
}, imgInfoWrap);
var newParagraph = createElement("p", {
"id": "imgVotes",
"class": ["votes", "alignic", "flex", "cursdef", "cw"]
}, imgInfoWrap);
var newParagraph = createElement("p", {
"id": "imgAverage",
"class": ["average", "alignic", "flex", "cursdef", "cw"]
}, imgInfoWrap);
var imgViews = document.getElementById("imgViews");
var imgVotes = document.getElementById("imgVotes");
var imgAverage = document.getElementById("imgAverage");
imgViews.innerText = $views;
imgVotes.innerText = $votes;
imgAverage.innerText = $average;
var newDiv = createElement("div", {
"id": "imgInnerWrap",
"class": ["relative", "flex"]
}, innerGlobalRating);
var imgInnerWrap = document.getElementById("imgInnerWrap");
var newDiv = createElement("div", {
"id": "imgInner",
"class": ["imgInner", "relative"]
}, imgInnerWrap);
var imgInner = document.getElementById("imgInner");
var newImg = createElement("img", {
"id": "imgSrc",
"class": ["babeImg", "boxsb", "show"],
"src": imgSrc
}, imgInner);
var starWrapper = document.getElementById("starWrapper");
var imgInner = document.getElementById("imgInner");
var newDiv = createElement("div", {
"id": "starWrapper",
"class": ["starWrapper", "flex", "center", "flex-drr", "absolute", "col100", "bot0"]
}, imgInner);
var starWrapper = document.getElementById("starWrapper");
var imgInner = document.getElementById("imgInner");
var newDiv = createElement("input", {
"id": "imgValue",
"class": ["absolute", "displayn"],
"type": "radio",
"value": jsonId
}, imgInner);
if (content === "newImg") {
for (i = 5; i > 0; i--) {
var newDiv = createElement("input", {
"id": "vote" + i,
"class": ["vote", "displayn"],
"type": "radio",
"name": "vote",
"value": i
}, starWrapper);
var newDiv = createElement("label", {
"id": "voteLabel" + i,
"class": ["voteHover"],
"htmlFor": "vote" + i
}, starWrapper);
}
starRating();
} else if (content === "ratedImg") {
var newDiv = createElement("div", {
"id": "shuffleImgWrap",
"class": ["shuffleImgWrap", "absolute", "top0", "right0", "mar15"]
}, imgInner);
var shuffleImgWrap = document.getElementById("shuffleImgWrap");
var newDiv = createElement("img", {
"id": "shuffleImg",
"class": ["shuffleImg"],
"src": "assets/img/refresh.png",
"alt": "refresh"
}, shuffleImgWrap);
shuffleRefresh();
alert("newImg");
}
setTimeout(slideIn, 500);
function slideIn() {
var globalRating = document.getElementById("globalRating");
if (hasClass(globalRating, "leftOut")) {
globalRating.classList.remove("leftOut");
}
globalRating.classList.add("leftIn");
}
}
if (content === "versus") {
var newDiv = createElement("div", {
"id": "innerGlobalRating",
"class": ["innerGlobalRating", "flex", "bgc1", "boxsb", "leftIn", "relative"]
}, globalRating2);
var innerGlobalRating = document.getElementById("innerGlobalRating");
var newDiv = createElement("img", {
"id": "vs1",
"class": ["vs1", "babeVersus", "borb2"],
"src": "assets/img/1.jpg"
}, innerGlobalRating);
var vs1 = document.getElementById("vs1");
var newDiv = createElement("input", {
"id": "versus1",
"class": ["absolute", "top0", "left0"],
"type": "radio",
"name": "versus"
}, innerGlobalRating);
var newDiv = createElement("label", {
"class": ["trophy", "absolute", "top0", "left0", "mar10"],
"htmlFor": "versus1"
}, innerGlobalRating);
var newDiv = createElement("img", {
"id": "versusIcon",
"class": ["versusIcon", "flex", "center", "mar10", "bgc2"],
"src": "assets/img/icons/versusIcon.png"
}, globalRating2);
var versusIcon = document.getElementById("versusIcon");
var newDiv = createElement("div", {
"id": "innerGlobalRating2",
"class": ["innerGlobalRating2", "flex", "bgc1", "boxsb", "rightIn", "relative"]
}, globalRating2);
var innerGlobalRating2 = document.getElementById("innerGlobalRating2");
var newDiv = createElement("img", {
"id": "vs2",
"class": ["vs2", "babeVersus", "borb2"],
"src": "assets/img/2.jpg"
}, innerGlobalRating2);
var vs2 = document.getElementById("vs2");
var newDiv = createElement("input", {
"id": "versus2",
"class": ["absolute", "top0", "right0"],
"type": "radio",
"name": "versus"
}, innerGlobalRating2);
var newDiv = createElement("label", {
"class": ["trophy", "absolute", "top0", "right0", "mar10"],
"htmlFor": "versus2"
}, innerGlobalRating2);
} else if (content === "donation") {
var newDiv = createElement("div", {
"id": "innerGlobalRating",
"class": ["innerGlobalRating", "flex", "bgc1", "boxsb"]
}, globalRating);
var innerGlobalRating = document.getElementById("innerGlobalRating");
var newDiv = createElement("div", {
"id": "donationWrapper",
"class": ["donationWrapper", "pad20"]
}, innerGlobalRating);
var donationWrapper = document.getElementById("donationWrapper");
var newDiv = createElement("p", {
"id": "donationText",
"class": ["donationText", "pad10"]
}, donationWrapper);
var donationText = document.getElementById("donationText");
donationText.innerText = "Contribuate to keep our website running 2";
var newDiv = createElement("button", {
"id": "buttonNo",
"class": ["buttonNo", "pad20"]
}, donationWrapper);
var buttonNo = document.getElementById("buttonNo");
buttonNo.innerText = "No";
var newDiv = createElement("a", {
"id": "buttonYes",
"class": ["buttonYes", "pad20"],
"href": "index.php?page=contribuate",
"target": "_blank"
}, donationWrapper);
var buttonYes = document.getElementById("buttonYes");
buttonYes.innerText = "Yes";
}
}
}
}
;
http.send(params);
}
}
newImage.php
require_once '../includes/db.php';
require_once '../includes/functions.php';
$dbCon = dbCon();
if(isset($_POST['voteValue'])){
$voteValue = $_POST['voteValue'];
} else{
$voteValue = 0;
}
if(isset($_POST['imgValue'])){
$imgValue = $_POST['imgValue'];
} else{
$imgValue = 0;
}
$checked = $_POST['checked'];
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$sql = "SELECT user_ip, user_source FROM rating_users WHERE user_ip = $ip AND user_source = $imgValue";
$result = $dbCon->query($sql);
if ($result->num_rows === 0) {
$stmtt = $dbCon->prepare("INSERT INTO rating_users (user_ip, user_vote, user_source) VALUES (?, ?, ?)");
$stmtt->bind_param('iii', $ip, $voteValue, $imgValue);
$stmtt->execute();
$stmt = $dbCon->prepare("UPDATE rating SET
votes = votes + 1,
rating = rating + ? WHERE id = ?");
$stmt->bind_param('ii', $voteValue, $imgValue);
$stmt->execute();
}
$sql = " SELECT user_ip FROM rating_users WHERE user_ip = $ip";
$result = $dbCon->query($sql);
if ($result->num_rows > 0) {
$har_stemt = 'true';
$sql = "SELECT id FROM rating WHERE category IN ($checked)";
$result_user_stemmer = $dbCon->query($sql);
$arr_alle_billeder;
$arr_alle_billeder_length = count($arr_alle_billeder);
while ($obj = $result_user_stemmer->fetch_object()) {
$arr_alle_billeder[] = $obj->id;
}
$arr_alle_billeder_int = [];
$arr_alle_billeder_length = count($arr_alle_billeder);
foreach ($arr_alle_billeder as $key => $val) {
$arr_alle_billeder_int[$key] = intval($val);
}
$sql = "SELECT user_source FROM rating_users WHERE user_ip = $ip";
$result_user_stemmer = $dbCon->query($sql);
// LAVER #2 ARRAY MED ALLE DE STEMTE BILLEDER
$arr_user_har_stemt_paa;
while ($obj = $result_user_stemmer->fetch_object()) {
// for hver user_source billedet IKKE skal vises
$arr_user_har_stemt_paa[] = $obj->user_source;
}
$arr_resterende_billeder = array_diff($arr_alle_billeder_int, $arr_user_har_stemt_paa);
$random_key = array_rand($arr_resterende_billeder);
$id = $arr_resterende_billeder[$random_key];
function myDice() {
$dice = rand(1, 100);
if ($dice > 0 && $dice <= 50) {
return 1;
} else if ($dice > 50 && $dice <= 99) { //75%
return 2;
} else if ($dice > 99 && $dice <= 100) { //10%
return 3;
}
}
$dice = myDice();
if ($dice === 1) {
if ($id) {
$sql = "SELECT views, votes, rating FROM rating WHERE id = $id";
$result = $dbCon->query($sql);
$result = $result->fetch_object();
$views = $result->views;
$votes = $result->votes;
$rating = $result->rating;
$average = averageRate($rating, $votes);
$imgSrc = "assets/img/" . $id . ".jpg";
$arr = ['content' => 'newImg', 'imgSrc' => $imgSrc, 'id' => $id, 'checked' => $checked, 'views' => $views, 'votes' => $votes, 'average' => $average, 'dice' => $dice];
$stmt = $dbCon->prepare("UPDATE rating SET
views = views + 1 WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
echo json_encode($arr);
} else { //$sql = "SELECT id, views, votes, rating FROM rating WHERE id <> $imgValue AND category IN ($checked) ORDER BY RAND() LIMIT 1";
//$sql = "SELECT id, views, votes, rating FROM rating WHERE category IN ($checked) AND id <> $imgValue ORDER BY RAND() LIMIT 1";
$sql = "SELECT id, views, votes, rating FROM rating WHERE category IN ($checked) AND id <> $imgValue ORDER BY RAND() LIMIT 1";
$result = $dbCon->query($sql);
$result = $result->fetch_object();
$id = $result->id;
$views = $result->views;
$votes = $result->votes;
$rating = $result->rating;
$sql = "SELECT user_vote FROM rating_users WHERE user_ip = $ip AND user_source = $id";
$result1 = $dbCon->query($sql);
$result1 = $result1->fetch_object();
$user_vote = $result1->user_vote;
$imgSrc = "assets/img/" . $id . ".jpg";
$average = averageRate($rating, $votes);
$arr = ['content' => 'ratedImg', 'imgSrc' => $imgSrc, 'id' => $id, 'checked' => $checked, 'views' => $views, 'votes' => $votes, 'average' => $average, 'user_vote' => $user_vote, 'dice' => $dice];
echo json_encode($arr);
}
}
if ($dice === 2) {
$arr = ['content' => 'versus', 'dice' => $dice, 'vs1' => 'someImg1', 'vs2' => 'someImg2'];
echo json_encode($arr);
}
if ($dice === 3) {
$arr = ['content' => 'donation', 'dice' => $dice];
echo json_encode($arr);
}
}