I have a copy script built in to the page I am working on, and when the copy JS is inline, it works great, but as soon as I moved it external, it produces the following error:
copy.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null
I am unsure why because when inline there is no issues. Copy of the section code is:
<?php
$connect = mysqli_connect("localhost", "brandina_templat", "REMOVED", "brandina_templates");
$catresult = "SELECT * FROM categories";
$catquery = mysqli_query($connect,$catresult);
$catquery2 = mysqli_query($connect,$catresult);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Templates Sheet | Brandin Arsenault's</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/tabcontent.js"></script>
<link href="css/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h1 align="center">Templates Sheet</h1>
<center><ul class="tabs">
<?php
if(!$catquery)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
echo "<li class='tab-link' data-tab='$tabname'>$catname</li>";
}
?>
</ul>
<?php
if(!$catquery2)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery2))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
$result = "SELECT * FROM templates WHERE category=$number";
$query = mysqli_query($connect,$result);
echo "<div id='$tabname' class='tab-content'>
<table><center>";
$c = 0;
$n = 3;
if(!$query)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($query))
{
$id=$row['id'];
$longname=$row['longname'];
$shortname=$row['shortname'];
$text=$row['text'];
if($c % $n == 0 && $c != 0)
{
echo '</tr><tr>';
}
$c++;
echo "
<td>
<center><b>$longname</b></center><textarea id='$id' cols='25' rows='3'>$text</textarea><br /><button id='$shortname'>Copy</button>
</td>
<script>
var shortname = '$shortname';
</script>";
}
echo "</center></table></div>";
}
?>
<script src='js/copy.js'></script>
</center>
</div>
</body>
</html>
copy.js is:
document.getElementById(shortname).addEventListener('click', function() {
copyToClipboardMsg(document.getElementById('$id'), 'msg');
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = 'Copy not supported or blocked. Press Ctrl+c to copy.'
} else {
msg = 'Text copied to the clipboard.'
}
if (typeof msgElem === 'string') {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
setTimeout(function() {
msgElem.innerHTML = '';
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = '_hiddenCopyText_';
var isInput = elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA';
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement('textarea');
target.style.position = 'absolute';
target.style.left = '-9999px';
target.style.top = '0';
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand('copy');
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === 'function') {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = '';
}
return succeed;
}
Thanks in advance!
The variable $shortname exists when you use the inline code, but when you move your code to external it doesn't exists anymore.
You can use:
<script>
var shortname = '$shortname';
</script>
<script src='js/copy.js'></script>
And in your copy.js file you should use:
document.getElementById(shortname).addEventListener('click', function() {
Otherwise - the javascript code is looking for element that it's id is $shortname, and you don't really have one with the value.
Related
I'm trying to do it so when a user checks a checkbox it gets the Email to a text field and when the user unchecks it it deletes the text field, here's the code that I've tried to use that's not working.
The php code:
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\" id=\"{$infoItems['EmailGeral']}\"".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."');\"/>
</tr>
";
}
?>
And the javascript:
<script>
function emailNextWithAddress(chk,address) {
if(chk.checked === true){
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
} else {
var nextEmail, inside_where;
nextEmail.value = address;
nextEmail.className = 'delemail';
inside_where = document.getElementById(<?php echo $infoItems['EmailGeral'] ?>);
inside_where.parentElement.removeChild(nextEmail);
return false;
}
}
</script>
You could add an id as the last parameter, and using it on your function :
<td><input type=\"checkbox\" id=\"{$infoItems['EmailGeral']}\"".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."', this.id);\"/></td>
<script>
function emailNextWithAddress(chk,address,id) {
if(chk.checked === true){
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
} else {
var nextEmail, inside_where;
nextEmail.value = address;
nextEmail.className = 'delemail';
inside_where = document.getElementById(id);
inside_where.parentElement.removeChild(nextEmail);
return false;
}
}
</script>
at least you're missing some quotes around that id
pick whether double/single vs single/double quotes:
document.getElementById("<?php echo $infoItems['EmailGeral'] ?>")
document.getElementById('<?php echo $infoItems["EmailGeral"] ?>')
The snippet of php/html was missing a closing </td> tag after the checkbox.
The javascript function could, I believe, be simplified a little like this. I made an assumption here in that the new input element should be appended to the current table row - I could not determine what the element with id addEmail was or where it was. The below should append a new text field in the same cell as the checkbox, populate with the email address when checked and remove when the checkbox is unchecked.
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
$name=$infoItems['Nome'];
$email=$infoItems['EmailGeral'];
$checked=$infoItems['Enviado'] ? 'checked' : '';
echo "
<tr>
<td>$name</td>
<td>$email</td>
<td><input type='checkbox' id='{$email}' {$checked} onclick='emailNextWithAddress( this );' /></td>
</tr>";
}
?>
<script>
function emailNextWithAddress( chk ) {
try{
if( chk.checked === true ){
var nextEmail;
nextEmail = document.createElement('input');
nextEmail.value = chk.id;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
chk.parentNode.appendChild( nextEmail );
} else {
chk.parentNode.removeChild( chk.parentNode.querySelector('input[ name="email[]" ]') );
}
return false;
}catch( err ){
console.info( err.message )
}
}
</script>
I am trying to detect a keypress using the jQuery keyup function, but it does not seem to work in Firefox. Though it does work in Chrome, Edge, IE and Opera.
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
".textfield" is an iframe with designmode = 'on' So I'm trying to detect a keyup within a editable iframe.
Here's my iframe, nothing special:
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
EDIT: (It's one of my first websites, so don't mind the bad code)
HTML
<head>
<title>Notepad - A minimalistic, free online text editor for your notes</title>
<meta charset="utf-8"/>
<meta name="description" content="Notepad is a free, minimalistic, online text editor for quickly writing down, saving and sharing your notes."/>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="filesaver/filesaver.js"></script>
<link href="https://fonts.googleapis.com/css?family=Khula|Roboto|Open+Sans|Barrio|Cairo|Cantarell|Heebo|Lato|Open+Sans|PT+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<!-- Fonts -->
<script>
WebFont.load({
google: {
families: ['Cantarell', "Open Sans"]
}
});
</script>
</head>
<body onload="enableEdit('dark'); handlePaste(); handleDrop(); retrieveNote(); createCookie();">
<!-- Facebook & Twitter Share -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/nl_NL/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="social">
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&src=sdkpreparse" style="vertical-align:top;zoom:1;*display:inline">Share</a></div>
<a class="twitter-share-button" href="https://twitter.com/intent/tweet"></a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<!-- Page -->
<div id="page">
<!-- Textfield -->
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
<!-- Toolbar -->
<div id="toolbar">
<h1 class="button" id="btn_bold" onclick="bold();" onmouseenter="onMouseEnter('btn_bold');" onmouseleave="onMouseLeave('btn_bold');"><b>B</b></h1>
<h1 class="button" id="btn_ita" onclick="italic();" onmouseenter="onMouseEnter('btn_ita');" onmouseleave="onMouseLeave('btn_ita');"><i>I</i></h1>
<h1 class="button" id="btn_und" onclick="underline();" onmouseenter="onMouseEnter('btn_und');" onmouseleave="onMouseLeave('btn_und');"><u>U</u></h1>
<img src="img/theme_dark.png" alt="Change theme" class="button theme" id="btn_theme" onclick="changeTheme();" onmouseenter="onMouseEnter('btn_theme');" onmouseleave="onMouseLeave('btn_theme')"; alt="Change theme." title="Theme"></img>
<img src="img/save.png" type="button" id="btn_save" value="submit" onclick="post();" class="button theme" alt="Save note." onmouseenter="onMouseEnter('btn_save');" onmouseleave="onMouseLeave('btn_save')" title="Save note"/>
<img src="img/cloud.png" type="button" id="btn_down" onclick="download();" class="button theme" alt="Download note" onmouseenter="onMouseEnter('btn_down');" onmouseleave="onMouseLeave('btn_down')" title="Download note"/>
<h1 class="button" id="btn_plus" onmousedown="changeFontSize(3);" onmouseenter="onMouseEnter('btn_plus');" onmouseleave="onMouseLeave('btn_plus');">+</h1>
<h1 class="button" id="btn_minus" onmousedown="changeFontSize(-3);" onmouseenter="onMouseEnter('btn_minus');" onmouseleave="onMouseLeave('btn_minus');">-</h1>
</div>
<div id="result"></div>
</div>
<?php
require("dbconnect.php");
$id = 0;
$idvar = $_GET['id'];
if ($idvar != null) {
$sel = "SELECT text from content WHERE id = $idvar";
} else {
$sel = "SELECT text from content WHERE id = 0";
}
$result = mysqli_query($connection, $sel);
if (mysqli_num_rows($result) == 1) {
while ($r = mysqli_fetch_array($result)) {
$content = str_replace('"', '"', $r["text"]);
}
} else {
header("Location: index.html");
}
$result = mysqli_query($connection, "SELECT id FROM content ORDER BY id DESC LIMIT 1;");
if (mysqli_num_rows($result) > 0) {
$lastid = mysqli_fetch_row($result);
}
?>
<div id="hid" style="display:none;" data-info="<?php echo $content; ?>"></div>
<script type="text/javascript">
function post() {
if (!saved) {
var content = getContent();
$.post("note.php", {posttext:content}, function (data) {});
var lastid = "<?php echo $lastid[0]; ?>";
if (content != "") {
increment++;
lastid = parseInt(lastid) + increment;
alert("Note saved at:\nnotepad.com/index.html?id=" + lastid);
document.getElementById("btn_save").style.opacity = "0.3";
document.getElementById("btn_save").title = "Saved at:\nnotepad.com/index.html?id=" + lastid;
saved = true;
} else {
alert("Empty note");
}
}
}
</script>
<script type="text/javascript" src="script.js"></script>
</body>
JavaScript
var color_text;
var color_button_light;
var color_button_dark;
var color_background;
var color_hover;
var brightness;
var font_size = 32;
var saved = false;
var mouseObj;
function getContent() {
return textfield.document.body.innerHTML;
}
var increment;
function download() {
if (getContent() != "") {
var blob = new Blob([getContent()], {type: "text/plain;charset=utf-8"});
saveAs(blob, "note");
} else {
alert("Empty note");
}
}
function retrieveNote() {
var info = $("#hid").data("info");
textfield.document.body.innerHTML = info;
}
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
function enableEdit(theme) {
increment = 0;
// Themes
if (theme === 'dark') {
color_text = "#757575";
color_button_light = "#303030";
color_button_dark = "#646464";
color_hover = "#535353";
brightness = 125;
color_background = "#151515";
} else if (theme === 'hacker') {
color_text = "#00BB00";
color_button_light = "#202020";
color_button_dark = "#00BB00";
color_hover = "#009900";
brightness = 125;
color_background = "#000000";
} else if (theme === 'light') {
color_text = "#999";
color_button_light = "#BBBBBB";
color_button_dark = "#757575";
color_hover = "#646464";
brightness = 90;
color_background = "#EEEEEE";
}
// Background Color
document.body.style.backgroundColor = color_background;
document.getElementById("toolbar").backgroundColor = color_background;
// Textfield
textfield.document.designMode = 'on';
var tag = "<link href='https://fonts.googleapis.com/css?family=Open+Sans|Heebo|Lato' rel='stylesheet'><style>body{font-family:consolas, heebo;}</style>"
$(".textfield").contents().find("head").append(tag);
textfield.document.body.style.fontSize = font_size + "px";
textfield.document.body.style.color = color_text;
textfield.document.body.style.padding = "20px";
textfield.document.body.style.tabSize = "4";
textfield.document.body.style.whiteSpace = "pre-wrap";
textfield.document.body.style.wordWrap = "break-word";
textfield.document.body.style.lineHeight = "1.4";
textfield.focus();
// Buttons
document.getElementById("btn_bold").style.color = color_button_light;
document.getElementById("btn_ita").style.color = color_button_light;
document.getElementById("btn_und").style.color = color_button_light;
document.getElementById("btn_plus").style.color = color_button_dark;
document.getElementById("btn_minus").style.color = color_button_dark;
}
function handlePaste() {
textfield.document.addEventListener("paste", function(evnt) {
evnt.preventDefault();
var text = evnt.clipboardData.getData("text/plain");
document.getElementById("btn_save").style.opacity = "1";
saved = false;
textfield.document.execCommand("insertText", false, text);
});
}
function handleDrop() {
textfield.document.addEventListener("drop", function (evnt) {
evnt.preventDefault();
document.getElementById("btn_save").style.opacity = "1";
saved = false;
var text = evnt.dataTransfer.getData("text/plain");
textfield.document.execCommand("insertText", false, text);
});
}
var sources = ["theme_dark.png", "theme_light2.png", "theme_hacker.png"];
var sources2 = ["save_dark.png", "save.png", "save_hacker.png"];
var themes = ["dark", "light", "hacker"];
var iterator;
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function createCookie() {
if (getCookie("theme") == "") {
iterator = 0;
} else {
iterator = getCookie("theme");
}
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
}
function changeTheme () {
createCookie();
if (iterator < sources.length-1) {
iterator++;
} else {
iterator = 0;
}
document.cookie = "theme=" + iterator + ";expires=Date.getTime() + 60 * 60 * 24 * 365 * 10;";
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
onMouseEnter('btn_theme');
}
function bold() {
textfield.document.execCommand("bold", false, null);
}
function italic() {
textfield.document.execCommand("italic", false, null);
}
function underline() {
textfield.document.execCommand("underline", false, null);
}
function changeFontSize (amount) {
font_size += amount;
textfield.document.body.style.fontSize = font_size + "px";
}
function onMouseEnter(id) {
mouseObj = id;
if (mouseObj != 'btn_theme' && mouseObj != 'btn_save') {
document.getElementById(mouseObj).style.color = color_hover;
} else {
document.getElementById(mouseObj).style.filter = "brightness(" + brightness + "%)";
}
}
function onMouseLeave(id) {
mouseObj = null;
}
setInterval(function() {
var isBold = textfield.document.queryCommandState("Bold");
var isItalic = textfield.document.queryCommandState("Italic");
var isUnderlined = textfield.document.queryCommandState("Underline");
if (isBold == true && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_dark;
} else if (isBold == false && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_light;
}
if (isItalic == true && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_dark;
} else if (isItalic == false && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_light;
}
if (isUnderlined == true && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_dark;
} else if (isUnderlined == false && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_light;
}
if (mouseObj != 'btn_plus') {
document.getElementById("btn_plus").style.color = color_button_dark;
}
if (mouseObj != 'btn_minus') {
document.getElementById("btn_minus").style.color = color_button_dark;
}
if (mouseObj != 'btn_theme') {
document.getElementById("btn_theme").style.filter = "brightness(100%)";
}
if (mouseObj != 'btn_save') {
document.getElementById("btn_save").style.filter = "brightness(100%)";
}
},10);
PHP for saving the note
<?php
require("dbconnect.php");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_error();
}
if (isset($_POST["posttext"]) && !empty($_POST["posttext"])) {
$content = $_POST['posttext'];
$content = mysqli_real_escape_string($connection, $_POST["posttext"]);
$insert = "INSERT INTO content (text) VALUES ('$content')";
mysqli_query($connection, $insert);
$id = mysqli_insert_id($connection);
}
?>
you can use jquery ...
$(document).ready(function(){
$(".textfield").keyup(function() {
$("#btn_save").css("opacity", 1);
});
});
Okay, I fixed the problem. Apparently Firefox needs $(document).ready() to properly function for keypress events (haven't tested other events).
So your code should be:
$(document).ready(function(){
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
});
Instead of:
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
As I already said this is a problem that only occured in Firefox AFAIK.
This code works in Chrome, Firefox, Opera, Edge and Internet Explorer as of time of writing this answer.
I had a similar problem.
The mobile keyboards (in Firefox) don't emit keyup, keydown and keypress events.
So, I met the Text Composition events.
Something like this:
myInput = document.getElementById('myInput');
myInput.addEventListener('compositionupdate', (event) => {
setTimeout(() => {
applyFilter(event)
});
})
The setTimeOut was necessary to wait input value receipt the keyboard value before call my function.
I have some php and html code and a small bit of JavaScript. Its a like system. Click the like button or dislike button and when you exit/leave the page the JavaScript and ajax runs a php file to update the database with the changes.(+1 to likes or +1 to dislikes or -1 to dislikes etc.) There is one problem. I click like/dislike and then i leave/ refresh page and the likes have not changed in value. If i dont click anything, which means im not updating the database and i refresh/leave a second time the likes are updated on the screen to what they should be. The database gets updated when its suppose to, its the code that dosnt use the new value for whatever reason. Here's my code:
<?php
session_start();
error_reporting(0);
$GOTID = $_GET['id'];
$GOTtitle = $_GET['title'];
include_once "mysql_connect.php";
include_once "like.php";
//include_once "dislike.php";
$email ='';
$log = null;
$log1 = null;
if(isset($_SESSION["ID"])){
$log1 = $_SESSION["ID"];
}else{
$log1=null;
}
if(isset($_SESSION["EMAIL"])){
$log = $_SESSION["EMAIL"];
$email = $_SESSION["EMAIL"];
// echo $email;
}else{
$log=null;
}
$_SESSION["EMAIL"] = $log;
$title = "";
$text="";
$tags = "";
$views = "";
$likes = "";
$dislikes = "";
$id = "";
$userid = "";
$date = "";
$thumbnail = "";
$imageext = "";
$texttype = "";
$data = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row = mysql_fetch_array($data)) {
$title = $row[0];
$descrip = $row[1];
$id = $row[2];
$userid = $row[3];
$date = $row[4];
$views = $row[5];
$likes = $row[6];
$dislikes = $row[7];
$thumbnail = $row[8];
$imagext = $row[10];
$videourl = $row[11];
}
if($likes != '0' || $dislikes !='0'){
$total = $likes + $dislikes;
$likebar = round(($likes / $total) * 100);
$finlikes = (($likebar * 150)/100);
}else{
$finlikes = 150;
}
$query5 = mysql_query("UPDATE `videos` SET `views` = `views`+1 WHERE `videos`.`id` = $GOTID;");
$stop = false;
$fetchlast = mysql_query("SELECT `id` FROM videos WHERE id=(SELECT MAX(id) FROM videos)");
$lastrow = mysql_fetch_row($fetchlast);
$lastid = $lastrow[0];
for ($i=1; $i <= $lastid; $i++) {
if($GOTID == $id){
$stop = true;
break;
}else{
if($i >=$lastid && $GOTID != $id){
$stop = false;
header('HTTP/1.0 404 Not Found');
$_GET['e'] = 404;
die();
exit;
}
}
}
$username = '';
$userrep = '';
$rank = '';
$imageData = '';
$currentname = mysql_query("SELECT * FROM allaccounts WHERE id=$userid");
while ($row = mysql_fetch_array($currentname)) {
$username = $row[0];
$rank = $row[3];
$userrep = $row[7];
$data = $row["image"];
$ext = $row["filetype"];
// $img1 = Img_Resize($data);
// $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
}
$liked = false;
$disliked = false;
$done = false;
$thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)");
$lastrow = mysql_fetch_row($thing);
$lastid = $lastrow[0];
if($lastid == null || $lastid == '0'){
$lastid = '1';
}
$state1 = '';
for ($i=1; $i <= $lastid+1; $i++) {
$current = mysql_query("SELECT * FROM likes WHERE id=$i");
while ($row = mysql_fetch_array($current)) {
$id1 = $row[0];
$userid1 = $row[1];
$state1 = $row[2];
$articleid1 = $row[3];
if($done == false){
if($email == $userid1 && $articleid1 == $id && $state1 == '1'){
$liked = true;
$disliked = false;
$done = true;
break;
}else{
$liked = false;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '0'){
$disliked = false;
$liked = false;
$done = true;
break;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '2'){
$disliked = true;
$liked = false;
$done = true;
break;
}else{
$disliked = false;
}
}
}
}
$donetitle = str_replace(" ", "-", $title);
$_SESSION["prevpage"] = "video/".$id."/".$donetitle."";
$lik = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($lik)) {
$Olikes = $row22[6];
}
$dis = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($dis)) {
$Odislikes = $row22[7];
}
?>
<html>
<head>
<title><?php echo $title;?></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"language="javascript" type="text/javascript"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript">
var likes = <?php echo $likes;?>;
var dislikes = <?php echo $dislikes;?>;
</script>
<div class = "container_24">
<header>
</header>
<div class = "main clearfix">
<div class ="grid_24 ">
<div id = "rectarticletop">
<a onclick='like()' id="likebtn"><img id="alike"src="img/icons/like.png" alt = "like"/></a>
<div id="dislikes"><div style="width:<?php echo($finlikes);?>;" id="likes"></div></div>
<a onclick="dislike()" id="dislikebtn"><img id="adislike" src="img/icons/dislike.png" alt = "dislike" /></a>
<p id= "likesnum"><?php echo $likes; ?></p>
<p id= "dislikesnum"><?php echo $dislikes; ?></p>
<script type="text/javascript">
var Liked = "<?php echo $liked;?>";
var Disliked = "<?php echo $disliked;?>";
var Art = "<?php echo $id;?>";
var User = "<?php echo $email;?>";
var olikes = "<?php echo $Olikes;?>";
var odislikes = "<?php echo $Odislikes;?>";
var state = "<?php echo $state1; ?>";
if(Liked == null){
Liked = false;
}
if(Disliked == null){
Disliked == false;
}
if(!Liked){
console.log("not liked!");
}
if(!Disliked){
console.log("not disliked!");
}
var loged = "<?php echo($log);?>";
window.onbeforeunload = function() {
$.ajax({
type: "GET",
url: 'dealLikes.php?article='+Art+'&user='+User+'&state=1&likes='+likes+'&dislikes='+dislikes+'&Olikes='+olikes+'&Odislikes='+odislikes+'&prev='+state+'',
success: function(data){
console.log("Its done!");
}
});
};
setInterval(function changetext(){
document.getElementById('likesnum').innerHTML = likes;
document.getElementById('dislikesnum').innerHTML = dislikes;
if(Liked){
document.getElementById('alike').src = "img/icons/like1.png";
}else{
document.getElementById('alike').src = "img/icons/like.png";
}
if(Disliked){
document.getElementById('adislike').src = "img/icons/dislike1.png";
}else{
document.getElementById('adislike').src = "img/icons/dislike.png";
}
},20);
function like(){
if(loged){
if(Liked){
likes-=1;
Liked = false;
// document.getElementById('alike').src = "img/icons/like.png";
}else if(Disliked){
dislikes-=1;
Disliked = false;
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else{
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
}
}else{
window.location = "login";
}
}
function dislike(){
if(loged){
if(Disliked){
dislikes-=1;
Disliked = false;
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else if(Liked){
likes-=1;
Liked = false;
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
//document.getElementById('alike').src = "img/icons/like.png";
}else{
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
}
}else{
window.location = "login";
}
}
</script>
</div>
</div>
</div>
</div>
</body>
</html>
What is wrong with the code that makes it not update the amount of likes on the first refresh but does update on the second refresh?
i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.
You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.
I am very new to jQuery/Javascript and have been trying to have a tabbed navigation menu closed on page load then open if clicked by the user. So far I haven't had any joy with editing the following file
function amshopby_start(){
$$('.block-layered-nav .form-button').each(function (e){
e.observe('click', amshopby_price_click_callback);
});
$$('.block-layered-nav .input-text').each(function (e){
e.observe('focus', amshopby_price_focus_callback);
e.observe('keypress', amshopby_price_click_callback);
});
$$('a.amshopby-more', 'a.amshopby-less').each(function (a){
a.observe('click', amshopby_toggle);
});
$$('span.amshopby-plusminus').each(function (span){
span.observe('click', amshopby_category_show);
});
$$('.block-layered-nav dt').each(function (dt){
dt.observe('click', amshopby_filter_show);
});
$$('.block-layered-nav dt img').each(function (img){
img.observe('mouseover', amshopby_tooltip_show);
img.observe('mouseout', amshopby_tooltip_hide);
});
$$('.amshopby-slider-param').each(function (item) {
param = item.value.split(',');
amshopby_slider(param[0], param[1], param[2], param[3], param[4], param[5], param[6]);
});
}
function amshopby_price_click_callback(evt) {
if (evt && evt.type == 'keypress' && 13 != evt.keyCode)
return;
var prefix = 'amshopby-price';
// from slider
if (typeof(evt) == 'string'){
prefix = evt;
}
else {
var el = Event.findElement(evt, 'input');
if (!Object.isElement(el)){
el = Event.findElement(evt, 'button');
}
prefix = el.name;
}
var a = prefix + '-from';
var b = prefix + '-to';
var numFrom = amshopby_price_format($(a).value);
var numTo = amshopby_price_format($(b).value);
if ((numFrom < 0.01 && numTo < 0.01) || numFrom < 0 || numTo < 0) {
return;
}
var url = $(prefix +'-url').value.gsub(a, numFrom).gsub(b, numTo);
amshopby_set_location(url);
}
function amshopby_price_focus_callback(evt){
var el = Event.findElement(evt, 'input');
if (isNaN(parseFloat(el.value))){
el.value = '';
}
}
function amshopby_price_format(num){
num = parseFloat(num);
if (isNaN(num))
num = 0;
return Math.round(num);
}
function amshopby_slider(width, from, to, max_value, prefix, min_value, ratePP) {
width = parseFloat(width);
from = parseFloat(from);
to = parseFloat(to);
max_value = parseFloat(max_value);
min_value = parseFloat(min_value);
var slider = $(prefix);
// var allowedVals = new Array(11);
// for (var i=0; i<allowedVals.length; ++i){
// allowedVals[i] = Math.round(i * to /10);
// }
return new Control.Slider(slider.select('.handle'), slider, {
range: $R(0, width),
sliderValue: [from, to],
restricted: true,
//values: allowedVals,
onChange: function (values){
this.onSlide(values);
amshopby_price_click_callback(prefix);
},
onSlide: function(values) {
var fromValue = Math.round(min_value + ratePP * values[0]);
var toValue = Math.round(min_value + ratePP * values[1]);
/*
* Change current selection style
*/
if ($(prefix + '-slider-bar')) {
var barWidth = values[1] - values[0] - 1;
if (values[1] == values[0]) {
barWidth = 0;
}
$(prefix + '-slider-bar').setStyle({
width : barWidth + 'px',
left : values[0] + 'px'
});
}
if ($(prefix+'-from')) {
$(prefix+'-from').value = fromValue;
$(prefix+'-to').value = toValue;
}
if ($(prefix + '-from-slider')) {
$(prefix + '-from-slider').update(fromValue);
$(prefix + '-to-slider').update(toValue);
}
}
});
}
function amshopby_toggle(evt){
var attr = Event.findElement(evt, 'a').id.substr(14);
$$('.amshopby-attr-' + attr).invoke('toggle');
$('amshopby-more-' + attr, 'amshopby-less-' + attr).invoke('toggle');
Event.stop(evt);
return false;
}
function amshopby_category_show(evt){
var span = Event.findElement(evt, 'span');
var id = span.id.substr(16);
$$('.amshopby-cat-parentid-' + id).invoke('toggle');
span.toggleClassName('minus');
Event.stop(evt);
return false;
}
function amshopby_filter_show(evt){
var dt = Event.findElement(evt, 'dt');
dt.next('dd').down('ol').toggle();
dt.toggleClassName('amshopby-collapsed');
Event.stop(evt);
return true;
}
function amshopby_tooltip_show(evt){
var img = Event.findElement(evt, 'img');
var txt = img.alt;
var tooltip = $(img.id + '-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.className = 'amshopby-tooltip';
tooltip.id = img.id + '-tooltip';
tooltip.innerHTML = img.alt;
document.body.appendChild(tooltip);
}
var offset = Element.cumulativeOffset(img);
tooltip.style.top = offset[1] + 'px';
tooltip.style.left = (offset[0] + 30) + 'px';
tooltip.show();
}
function amshopby_tooltip_hide(evt){
var img = Event.findElement(evt, 'img');
var tooltip = $(img.id + '-tooltip');
if (tooltip) {
tooltip.hide();
}
}
function amshopby_set_location(url){
if (typeof amshopby_working != 'undefined'){
return amshopby_ajax_request(url);
}
else {
return setLocation(url);
}
}
document.observe("dom:loaded", function() { amshopby_start(); });
The element that I am trying to manipulate is contained in this file
<?php if($this->canShowBlock()): ?>
<div class="block block-layered-nav">
<div class="block-title">
<strong><span><?php echo $this->__('Shop By') ?></span></strong>
</div>
<?php echo $this->getStateHtml() ?>
<div class="block-content">
<?php if($this->canShowOptions()): ?>
<!-- <p class="block-subtitle">--><?php //echo $this->__('Shopping Options') ?><!--</p>-->
<ul id="narrow-by-list">
<li>
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<div class="opt-row">
<dl class="opt-row">
<dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd>
</dl>
</div>
<?php endif; ?>
<?php endforeach; ?>
</li>
</ul>
<script type="text/javascript">decorateDataList('narrow-by-list')</script>
<?php endif; ?>
<?php if ($this->getLayer()->getState()->getFilters()): ?>
<div class="actions"><?php echo $this->__('Clear All') ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
When the page loads I woul like to have the tabbed navigation menus closed but toggable to open by the user... Can anyone assist please?
From the admin panel, you can make any of your filters closed by default:-
Catalog > Improved Navigation > Filters
Select the relevant filter and set 'Collapsed' to 'Yes'.