Get value from javascript onclick in php - javascript

I am making an page with every video I upload to the database.
They are filtered by date and ordered by date. There is an onclick on every video with JavaScript. With all the value's it has to show on the website.
But when I click on the video it has to filter all the video´s with the tags they have. The only thing it does now, it shows the right tag with the video but not the right tag when I want to filter it. Then it gives me the tag from the video that is posted first.
How do I get the right tag value when there clicked on? when I want to filter the tags?
<?php
$query = $connectie->prepare("SELECT v.VideoID,v.Titel,v.Link,v.Omschrijving,o.Bestandspath, o.Bestandsnaam,o.Onderwerp,t.Naam, DATE_FORMAT(`postDate`,\"%e-%m-%Y %H:%i\")as tijd FROM video v join opdracht o on v.OpdrachtID = o.OpdrachtID JOIN videotag vt on v.VideoID = vt.VideoID
JOIN tag t on vt.TagID = t.TagID order by `postDate` ");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$link = $row['Link'];
$newLink = str_replace("watch?v=", "embed/", $link);
$data = file_get_contents('https://www.youtube.com/oembed?format=json&url=' . $link);
// echo $newLink;
$json = json_decode($data);
$thumbnail = $json->thumbnail_url;
$title = $json->title;
$onderwerp = $row['Onderwerp'];
$omschrijving = $row['Omschrijving'];
$filePath = $row['Bestandspath'];
$bestandsnaam = $row['Bestandsnaam'];
$videoid = $row['VideoID'];
$tagName = $row['Naam'];
echo 'tagname',$tagName;
echo
'
<div class="scrollbar">
<a id="videoList" name="video" href="#" onclick="getLink(\'' . htmlentities($newLink) . '\',\'' . htmlentities($title) . '\',\'' . htmlentities($onderwerp) . '\',\''.htmlentities($tagName) . '\',\'' . htmlentities($omschrijving) . '\',\'' . htmlentities($bestandsnaam) . '\',\'' . htmlentities($filePath) . '\')">
<img src="' .htmlentities($thumbnail) . '" width="235"/>
<p id="titelText"><b>' . htmlentities($title) . '</b></p>
</a>
</div>
<script>
function getLink(link,titel,onderwerp,tagNaam,omschrijving,bestandsnaam,bestandspath){
document.getElementById("videoFrame").src = link;
document.getElementById("videoFrame").style.display = "block";
document.getElementById("overzicht").style.width = "275px";
document.getElementById("panelInfo").style.display = "block";
document.getElementById("titelVideo").innerHTML = "<b>Titel</b>:"+titel+"<br>";
document.getElementById("onderwerp").innerHTML = "<b>Onderwerp</b>:"+onderwerp+"<br>";
document.getElementById("tagnaam").innerHTML = "<b>Tag</b>:" + tagNaam + "<br>";
document.getElementById("omschrijving").innerHTML = "<b>Omschrijving</b>:"+omschrijving;
document.getElementById("bestand").download = bestandsnaam;
document.getElementById("bestand").href = bestandspath;
}
</script>';
}

Related

Updating id with javascript

Hi I am super new to php and coding in general and I have a question about updating my attribute with javascript. I currently have a loop which cycles through various assignmentNames. I need to update the id = popup-1 in order to have the loop be functional. Appreciate any help. Here is the PHP and script I have currently:
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "Assignments";
while($row = mysqli_fetch_array($result)){
echo '<div class="popup" id="popup-1">';
echo '<div class="overlay"></div>';
echo '<div class = "content">' . $row['dueDate'] . $row['className'] . '</div>';
echo '<div class="close-btn content" onclick="togglePopup()">×</div>';
echo '<div class = "btn-group">' . '<button onclick="togglePopup()">' . $row['assignmentName'] . '</button>' . '</div>';
echo '</div>';
echo '<script type="text/javascript">','updateId();','</script>';
}
}
function updateId() {
//initialize the index with 1, the item with 0 index is already in webpage.
var i = 1;
//Add after the element
var oldID = document.getElementById("popup-1");
oldID.id = "popup-1"+i;
//Increment the index
i++;;
}

How to use javascript and HTML to add a sql and button?

I have an application where I want to ADD an AND button that, than creates the option to add an AND statement to the query. This is the php and html code I have to do this at the moment. The problem is I don't know how to connect the php part to the javascript part to create a button that adds exacte the same code?
This the html code:
This is the php code:
<?php
include "connect.php";
$table = $_POST['tableSelected'];
$field = $_POST['fieldSelected'];
$attribute = $_POST['attributeSelected'];
$operator = $_POST['operatorSelected'];
$fieldList = $_POST['fieldList'];
if (!empty($table)){
if (!empty($fieldList)){
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326),6)";
} else {
$fieldstr = "";
}
$pairs = [];
foreach ($_POST['fieldSelected'] as $key => $field) {
if (!empty($field) && !empty($_POST['operatorSelected'][$key]) && !empty($_POST['attributeSelected'][$key])) {
$pairs[] = $field . " " . $_POST['operatorSelected'][$key] . " '" . $_POST['attributeSelected'][$key] . "'";
}
}
if (count($pairs) > 0) {
$sql .= ' WHERE ' . implode(' AND ', $pairs);
}
//echo ($sql);
?>
And this my html at the moment:
<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>
This is what I want:
Button click should produce something like it Javascript (jQuery):
newElement = $("#someSelector").clone(false);
// Some modification of new element. Change id for example
$(newElement).attr("id",newIdValue);
newElement.appendTo("#parentElement");

jQuery change input value on div mouseover

I'm trying to change an input value using jQuery mouse over.
Scenario: I got 5 div having different colors and user names. When mouseover a div the input text change (and for color input the background color) data according to database values, when change div the text displays new data.
using PHP I echo the part of the script to handle the mouseover function
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('$myId').mouseover( function () {
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
This work if i change mouseover() to hover(), but display only the first element, if i do a mouse over the second element data doesn't change.
Try this:
Put your script after body tag:
<body>
<div class="hh" id="1"></div>
<input type="text" id="uname" />
<input type="text" id="ucolor" />
<div class="hh" id="2"></div>
</body>
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('#$myId').mouseover( function () { // add # here
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
$myId = '2';
$uname = 'user2';
$ucolor = 'FFF555';
echo "<script>
$('#$myId').mouseover( function () { console.log('fdgfdg')
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
?>
In general the div or any DOM must have a unique ID value. Try using class selector(.) instead of ID selector(#).

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Adding comments into database with PHP (Using AJAX to prevent page reload)

I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).
At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.
I'd also like to be able to have the comment appear in the comments section below after submission if possible.
Thanks for your help
yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)
<?php //recaptcha_process.php
require_once("php/checklog.php");
require_once('php/functions.php');
require_once('php/db_connect.php');
include_once("php/home_start_logged.php");
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}else{
//CODE TO QUERY DATABASE TO GO HERE
//Capture form data, if anything was submitted
if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
if ($row['netflix'] == null){
$netflixLink = "";
}else{
$netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
}
if ($row['lovefilmInstant'] == null){
$lovefilmLink = "";
}else{
$lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
}
if ($row['blinkbox'] == null){
$blinkboxLink = "";
}else{
$blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
}
if ($row['itunes'] == null){
$iTunesLink = "";
}else{
$iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
}
if ($row['googlePlay'] == null){
$googleplayLink = "";
}else{
$googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
}
if ($row['amazon'] == null){
$amazonLink = "";
}else{
$amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
}
//Body content for film
$str_result = "<section>
<div class='sectionColumnThird'>
<img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
</div>
<div class='sectionColumnTwoThirds'>
<h2>" . $row['filmName'] . "</h2>
<p class='filmDate'>(" . $row['filmYear'] . ")</p>
<a class='formButton' href='#comments'>Jump to comments</a>
</div>
</section>
<section>
<h3>Not interested?</h3>
<a class='formButton' href='#yourfilm.php'>Find another film</a>
</section>
<section>
<h3>Rating</h3>
<p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
<p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
<p><span class='bold'>Metacritic:</span> " . $row['ratingMetacritic'] . "</p>
</section>
<section>
<h3>Synopsis</h3>
<p>" . $row['synopsis'] . "</p>
</section>
<section>
<h3>Trailer</h3>
<div class='videoWrapper'>
<iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
</div>
</section>
<section>
<h3>Cast & Crew</h3>
<p><span class='bold'>Director:</span> " . $row['director'] . "</p>
<p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
<p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
</section>
<section>
<h3>Details</h3>
<p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
<p><span class='bold'>Country:</span> " . $row['country'] . "</p>
<p><span class='bold'>Language:</span> " . $row['language'] . "</p>
</section>
<section>
<h3>Streaming Services</h3>"
. $netflixLink . $lovefilmLink . $blinkboxLink ."
</section>
<section>
<h3>Buy now</h3>"
. $iTunesLink . $googleplayLink . $amazonLink ."
</section>
<section>
<form id='frmFilmComments' action='yourfilm.php' method='post'>
<a id='comments' class='anchor'></a><h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p id='commentResult'></p>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
<input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' />
</form>";
$filmID=$row['filmID'];
mysqli_free_result($result);
//Print out Like it - Comments
$likeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='Yes' AND filmID=$filmID";
$likeitResult = mysqli_query($db_server, $likeitQuery);
if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($likeitResult)){
$str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($likeitResult);
$likedcomments = "<div class='half subSection'>
<h4>Liked it</h4>"
. $str_likedcomments .
"</div>";
//Print out disike it - Comments
$dislikeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='No' AND filmID=$filmID";
$dislikeitResult = mysqli_query($db_server, $dislikeitQuery);
if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($dislikeitResult)){
$str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($dislikeitResult);
$dislikedcomments = "<div class='half subSection'>
<h4>Disliked it</h4>"
. $str_dislikedcomments .
"</div>";
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
}
}else{
$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
//Comments
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$comment = clean_string($db_server, $_POST['commentBox']);
//Get any submitted comments and insert
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment!";
}
require_once('php/db_close.php');
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<?php echo $message; ?>
</div>
</div>
<?php
require_once('php/home_end.php');
?>
addCommentAJAX.js
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
$("#frmFilmComments").submit( function() {
return false;
});
function clearInput() {
$("#frmFilmComments :input").each( function() {
$(this).val('');
});
}
home_start_logged.php is simply a header template, I won't post it all but it contains:
<script src="js/addCommentAJAX.js" type="text/javascript"></script>
EDIT: Added more specific info about the error (see above).
there is not enough data to make an exact solution, but i see two problems :
1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit
2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database
So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.
http://api.jquery.com/event.preventdefault/
The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.
can you change this
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
to
function onclicksth() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
}
and change submitComment type to button? There is a better way to do this too:
//rough code including the submit and post data
$('form.frmFilmComments').on('submit', function() {
if(confirm('Do u want to input that field')){
fields-=1;
var obj = $(this),
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
$("#hdnlstcount").val(fields);
//console.log(fields);
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {
//do sth with success response
}
});
return false; //disable refresh
clearInput();
}
});

Categories