Looping through a jQuery statement - php

I'm using a field in one of my databases to store the song location... When I've got 1 song in the db it plays well onClick. But with 2 or more songs in the database, onClick they all play in sync. How do I loop through the jQuery append statement to act like a PHP while loop? Sorry, I'm still learning jQuery/Javascript... I actually run into this problem allot. So a solution would really help me!
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());
$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");
while($row = mysql_fetch_array($song_query)) {
echo "<span class='song'><b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
//echo '<img alt="" id="play" src="play.png" />';
//echo '<div id="audio"></div>';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#play').click(function() {
$("#audio").append('<audio autoplay="true" src="<?php echo $row['songuri'] ?>" /></audio>');
});
});
</script>
<img alt="" id="play" src="play.png" />
<div id="audio"></div>
<?php } ?>

This gives all your songs their own stop/play controls.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());
$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");
while($row = mysql_fetch_array($song_query)) {
echo "<div class='song' sid='".$row['idsongs']."' songuri='".$row['songuri']."'>";
echo "<b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
echo "<img class='play' src='play.png' /><br>";
echo "<div class='audio'></div>";
echo "<div class='stop'>Stop!</div>";
echo "</div>";
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.play').click(function() {
var songdiv = $(this).parent('div.song');
var songuri = songdiv.attr('songuri');
var sid = songdiv.attr('sid');
// stop this song if it's already playing
stopPlayer(sid);
// play
var audio = '<audio class="player" sid="'+sid+'" autoplay="true" src="'+songuri+'" /></audio>';
$(this).siblings('div.audio').html(audio);
});
$('.stop').click(function(){
var songuri = $(this).parent('div.song').attr('sid');
stopPlayer(songuri);
});
});
function stopPlayer(id) {
var p = $('.player[sid='+id+']');
if (p[0]) {
p[0].pause();
}
}
</script>

It appears to me that you've provided no mechanism to append your autoplay=true to the specific play button that was clicked -- you're appending it to all elements with #audio. Try generating unique ids for every play and div with audio so you can link the two together.
As a first stab, try this:
while($row = mysql_fetch_array($song_query)) {
echo "<span class='song'><b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
echo '<img alt="" id="' + "play-$row[idsongs]" + '" src="play.png" />';
echo '<div id="' + "audio-$row[idsongs]" +'"></div>';
This gives you unique identifiers for all your objects; I don't know JS well enough to suggest how to correlate the audio-$row[idsongs] when a play-$row[idsongs] has been clicked, but surely there must be some way to discover the id of the clicked object, change play to audio, and then append the HTML.

Related

How to output a mysql row by using Ajax?

How can i get the whole row based on div ID(or something like this) using Ajax?
<div id="1">something inside</div>
<div id="2">something inside</div>
<div id="3">something inside</div>
<div id="4">something inside</div>
<div id="5">something inside</div>
<div id="6">something inside</div>
<div id="results"></div>
If someone clicks on a div, a row with the same id should be shown from the mysql.
When someone clicks on the <div id="3">, it should load a row, with the id "3" from mysql into the result div.
So far i was only able to code this:
$("#smash").click(function(){
$.ajax({
url: "loaditems.php",
success: function(result){
$("#items").html(result);
}});
});
PHP
<?php
include "mysql.php";
$sql = "SELECT * FROM SmiteItems";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='item'>";
// Name
echo "<h3>" . $row["name"] . "</h3>";
// DIV INFO
echo "<div class='info'>";
// Picture
echo "<img src='img/" . $row["id"] . ".png'>";
// Table Values
echo "<table>";
// Power
if($row["power"]>0) {
echo "<tr><td>Power:</td><td> " . $row["power"] . "</td></tr>";
}
// Attack Speed
if($row["attspeed"]>0) {
echo "<tr><td>Attack speed:</td><td> " . $row["attspeed"] . "</td></tr>";
}
// Lifesteal
if($row["lifesteal"]>0) {
echo "<tr><td>Lifesteal:</td><td> " . $row["lifesteal"] . "</td></tr>";
}
// Penetration
if($row["penetr"]>0) {
echo "<tr><td>Penetration:</td><td> " . $row["penetr"] . "</td></tr>";
}
// Physical Def
if($row["physdef"]>0) {
echo "<tr><td>Physical:</td><td> " . $row["physdef"] . "</td></tr>";
}
// Magical Def
if($row["magdef"]>0) {
echo "<tr><td>Magical:</td><td> " . $row["magdef"] . "</td></tr>";
}
// Health
if($row["health"]>0) {
echo "<tr><td>Health:</td><td> " . $row["health"] . "</td></tr>";
}
// HP regen
if($row["hp5"]>0) {
echo "<tr><td>HP5:</td><td> " . $row["hp5"] . "</td></tr>";
}
// Movement Speed
if($row["mspeed"]>0) {
echo "<tr><td>Movement:</td><td> " . $row["mspeed"] . "</td></tr>";
}
// Cooldown
if($row["cdown"]>0) {
echo "<tr><td>Cooldown:</td><td> " . $row["cdown"] . "%</td></tr>";
}
// Mana
if($row["mana"]>0) {
echo "<tr><td>Mana:</td><td> " . $row["mana"] . "</td></tr>";
}
// MP5
if($row["mp5"]>0) {
echo "<tr><td>MP5:</td><td> " . $row["mp5"] . "</td></tr>";
}
// Crowd Control Reduction
if($row["ccr"]>0) {
echo "<tr><td>CCR:</td><td> " . $row["ccr"] . "</td></tr>";
}
// Stack YES output
if($row["stack"]==1) {
echo "<tr><td>Stack:</td><td> Yes</td></tr>";
}
// Item Type Aura Passive etc
if (!empty($row["itype"])){
echo "<tr><td>Type:</td><td> " . $row["itype"] . "</td></tr>";
}
// Table Close
echo "</table>";
// Item description
if (!empty($row["text"])){
echo "<div class='text'>";
//echo "<h4>Description:</h4>";
echo "<p>" . $row["text"] . "</p>";
echo "</div>";
}
echo "</div>"; // CLOSE DIV INFO
echo "</div>";
}
} else {
echo "<p>0 results</p>";
}
$conn->close();
?>
I know that my PHP isn't great, i just started learning it. There are also empty rows in my MySQL table, so i need to check if it's empty before adding it to the html.
First you need an onclick event on the divs. When a div is clicked, their id will be passed to the getrow() function.
<div id="1" onclick="getrow(this.id)">something inside</div>
<div id="2" onclick="getrow(this.id)">something inside</div>
<div id="3" onclick="getrow(this.id)">something inside</div>
<div id="4" onclick="getrow(this.id)">something inside</div>
<div id="5" onclick="getrow(this.id)">something inside</div>
<div id="6" onclick="getrow(this.id)">something inside</div>
<div id="results"></div>
Here is the getrow() function. The div id is passed through the variable divid and sent to loaditems.php
function getrow(clicked_id) {
$.ajax({
url: "loaditems.php",
data: {divid: clicked_id},
success: function(data){
$("#result").html(data);
}
});
}
Then just change your PHP query like this (presuming each row is represented by an incrementing ID). I have written this in PDO as this is what you should be using to keep your site secure.
$sql = $conn->("SELECT * FROM SmiteItems WHERE ID=:rowid");
$sql->bindParam(':rowid', $_POST['divid']);
$sql->execute();
if($sql->rowCount() > 0) { // if a row is returned
while($row = $sql->fetch()) {
// rest of your code
}
}
First you'll need a function call on an event such as onclick on each div
<div id="1" onclick="getresult(1)">something inside</div>
<div id="2" onclick="getresult(2)">something inside</div>
<div id="3" onclick="getresult(3)">something inside</div>
<div id="4" onclick="getresult(4)">something inside</div>
<div id="5" onclick="getresult(5)">something inside</div>
<div id="6" onclick="getresult(6)">something inside</div>
<div id="results"></div>
Then use ajax in the function to fetch results from the PHP file and display it into the results div
function getresult(id){
var xhr= new XMLHttpRequest();
var params = "id="+id;
var url = address of your php file
xhr.open('POST',url,true);
xhr.onload=function(){
if(this.status == 200)
var resultarray = json_decode(this.responseText);
//now you can access the data like an array in the variable resultarray and display it however you wish
}
xhr.send(params);
}
In the PHP file get the id using POST variable and execute your mysql query.
require('mysql.php');
$stmt = $con->prepare("SELECT * FROM SmiteItems WHERE id=?");
$stmt->bind_param("i",$id);
$id=$POST['id']; //get the id from post variable
$stmt->execute();
$result=$stmt->get_result();
echo json_encode($result);

How to get the id to set a session variable in php

This first part isn't having any issues now.
<?php
session_start();
while($row = $result->fetch_assoc()){
echo "<div id='name' style='margin-top:50px;'><h2>" . $row['name'] . "</h2>";
echo "<a href='nextPage.php'><img class='pic' src='".$row['imageURL']."' data-id='".$row['id']."' height='100px'/></a></div>";
echo "<div id='bio' style='border-bottom:1px solid #000;'><p>" . $row['bio'] . "</p></div>";
}
?>
<script type="text/javascript">
$(document).on('click', '.pic', function(){
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: 'setSession.php',
data: {myId: id}
});
});
</script>
After I click an image I just get php error messages telling me there is an undefined variable. I currently have 'setSession.php' as a separate page, not sure if it's supposed to be or not.
**Next Page**
<?php
session_start();
include("connect.php");
$result = mysqli_query($con, "select * from table");
mysqli_close($con);
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div class="wrapper">
<img src="<?php echo $row['imageURL'];?>" height="200px"/><br/>
<div class="textSection" style="text-align:center;">
<h2><?php echo $row['name'];?></h2>
<p>
<?php echo $row['bio'];?>
</p>
</div>
</div>
</body>
</html>
firstly, you should start session in that page like this.
session_start();
then access the session variable like this.
$_SESSION['your_key_here'];// this will return the value stored in session.
Put data attribute data-id on img tag and change ids into class since ids should be unique like so :
<img class='pic' src='" . $row['imageURL'] . "' data-id='" . $row['id'] . "' height='100px'/></a></div>";
And register click handler to img using its class together with AJAX request to set data id into session variable like so :
$(document).on('click', '.pic', function() {
var id = $(this).data('id'); // get id value from data-id attribute
$.ajax({
type : 'POST',
url : 'setSession.php',
data : {
myId : id
},
success : function(msg) { /* do something here for success request */ }
});
});
Finally. in setSession.php page :
<?php
session_start();
$_SESSION['id'] = $_POST['myId']; // this come from ajax request
echo "something"; // and this will available on ajax success callback
?>

Reconciling Show/Hide JQuery Script into PHP

I currently have some php script that outputs results from a query. I would like to add at the end two buttons that will show/hide the final element, but am not sure how to do this.
The following is my php script:
while($result = mysqli_fetch_array($iname))
{
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
//this is where I would like to add my two buttons, that would show the "hidden" content when clicked
And here is what I have written in an HTML script, that I would like to reconcile into the PHP output:
<!DOCTYPE html>
<html>
<head>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js></script>
<script>
$(document).ready(function(){
$("#hidden").hide();
$("#hide").click(function(){
$("#hidden").hide(500);
});
$("#show").click(function(){
$("#hidden").show(500);
});
});
</script>
</head>
<body>
<button id="show">Show</button>
<button id="hide">Hide</button>
<p id="hidden">
Some Random Text that will be shown when the buttons are clicked
</p>
</body>
</html>
Any suggestions as to how this should be done?
How about if you get the number of result rows with $num_rows = mysql_num_rows($result);
Then, put a counter in your loop.
$counter = 1;
$theClass="";
while($result = mysqli_fetch_array($iname))
{
if ($counter == mysql_num_rows($result);){
$theClass="showHide";
}
echo "<div class='$theClass'>";
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
echo "</div>
$counter++;
}
Then, apply your javascript to the div whose class="showHide"

Dumping PHP echo in jQuery

I'm loading images (pinpoints) onto a map and if you click on them they load a video URL in a DB. When I load the images using PHP I name their IDs the corresponding index in the MySQL so I can talk to them when I click on the images and attach an action to it, to load the correct video URL.
For some reason the PHP breaks the code.
<div id="satmap-div">
<div>
<?php
$sql = "SELECT * FROM btring_content";
$n = 1;
$result = $objCon->query($sql) or die('error in query:' . mysqli_error($objCon));
while($row = mysqli_fetch_assoc($result)) {
echo "<img id=" . $row['id'] . " class='pinpoint' src='img/pp.png'/>";
?>
<script>
$( "#satmap-div .pinpoint:nth-child(" + ( <?php echo (string)$n?> ) + ")" ).css( { "left": <?php echo (string)$row['leftPos']?>, "top": <?php echo (string)$row['topPos']?> } );
</script>
<?php
$n++;
}
?>
</div>
<img id="satmap" src="img/bigmap.gif"/>
</div>
$('#satmap-div > div').children('img').click(function() {
var index = $(this).attr('id');
<?php
$sql2 = "SELECT * FROM `btring_content` WHERE `id`=18";
$result2 = $objCon->query($sql2) or die('error in query:' . mysqli_error($objCon));
$row2 = mysqli_fetch_array($result2);
?>
$( "p" ).text( <?php echo (string)$row2['link']?> );
});
Change :
$( "p" ).text( <?php echo (string)$row2['link']?> );
to
$( "p" ).text( "<?php echo (string)$row2['link']?>" );
When displaying strings using the .text() function always qoute.
You are using the following line in your code:
echo "<img id=" . $row['id'] . " class='pinpoint' src='img/pp.png'/>";
This actually means your code will render as following:
<img id=3 class='pinpoint' src='img/pp.png'/>
As you can see, you are missing the quotes around id. Try using the following code instead:
echo "<img id='" . $row['id'] . "' class='pinpoint' src='img/pp.png'/>";
Further, your <script> is also missing ; in the PHP echo statements:
<script>
$( "#satmap-div .pinpoint:nth-child(" + ( <?php echo (string)$n?> ) + ")" ).css( { "left": <?php echo (string)$row['leftPos']?>, "top": <?php echo (string)$row['topPos']?> } );
</script>
Change it to:
<script>
$( "#satmap-div .pinpoint:nth-child(" + ( <?php echo (string)$n?> ) + ")" ).css( { "left": <?php echo (string)$row['leftPos']; ?>, "top": <?php echo (string)$row['topPos']; ?> } );
</script>

Using jQuery function in a php while loop

I'm having trouble with a jQuery script for voting on posts. I have a "frontpage" with a list of posts from a mysql db. On each post there is a little votebox you can either vote up or down.
jQuery/ajax script:
<script type="text/javascript">
$(document).ready(function() {
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
$('.plus-button').html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).attr('id');
$('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
success: function(data){
$('.minus-button').html(data);
}
});
});
});
</script>
Votebox.php
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
$postid = htmlentities($postid, ENT_QUOTES);;
include("connect.php");
//For test purposes
echo $postid;
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="plus-button liked" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
else{
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Frontpage:
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT 0,10");
if($sql1){
while($row = mysqli_fetch_array($sql1)){
$postloopid = $row['id'];
?>
<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</div><br />
<article class="slide"><?php echo nl2br($row['post']); ?></article>
<br />
<?php include("php/votebox.php"); ?>
<br />
by <a style="font-size:18px;" href="profile.php?id=<?php echo $row['submittedby']; ?>"><?php echo $row['submitteduser']; ?></a>
at <span style="font-size:12px;"><?php echo $row['added']; ?></span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=<?php echo $row['id']; ?>#commentfield"><?php echo $row['totalcomments']; ?> comments</a></span>
</div>
<?php
}
}
?>
The problem now is that when I click the votebox buttons it turns out I only get the postid from the first loaded post from the while loop. Another problem I have is that my total up- and downvotes changes in all the posts on the list, not the specific post.
Any ideas?
The Javascript code isn't in the loop, it can't reference postloopid. Or if it is, you're binding all buttons of the class every time through the loop, and clicking on them will run all the handlers, incrementing all the posts.
You should put the post ID as a data field in the button, and then access that from the Javascript:
echo '<div class="plus-button liked" data-postid="'+$postid+'" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="'+$postid+'" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
Then your Javascript can do:
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
I made the following changes to the JS:
Use $(this).data('postid') to get postid.
Only remove the disliked class from the sibling minus button, not all minus buttons on the page.
Put the returned HTML just in this element, not in all plus buttons. I pass this in the context: parameter, so that the success function can refer to it.
Alright lets go through your jQuery code(just the like function):
Bind click handler to all elements with the class plus-button
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
Remove disliked class from all elements with class minus-button
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
Set inner html of all elements with class plus-button
$('.plus-button').html(data);
}
});
});
What you want is to store the postid as an attribute on the posts, then use
var postid = $(this).attr('postid')
only remove the disliked class from the current element
$(this)
.parents('{element containing plus and minus button}')
.find('.minus-button')
.removeClass('disliked')
;
store reference to the clicked element
var $this = $(this); // Cool guys do this right in the beginning and use only this variable instead of $(this)
then in your ajax success handler you want to set only the html of the button you clicked, so you may use the reference you stored in the parent function scope
$this.html(data);
EDIT in regards to infinite scroll script
When parts of your page are dynamic, you want to bind the click handler to a static parent element of the dynamic content using:
$("#postsParent").on('click', '.plus-button', function () {/*handler*/})

Categories