How to output a mysql row by using Ajax? - php

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);

Related

how to change image from sql database during hover in php

PHP
I am trying to change the image during hover. For hover I used jquery, but the problem is that the first image is showing from the SQL database but the image is not changing while I already saved the second image in database
<?php
include('dbconnect.php');
$sql = "SELECT * FROM `products` JOIN `images` ON products.product_id=images.product_id";
$res = mysqli_query($conn, $sql);
echo "</h3> Total: " . mysqli_num_rows($res) . " Items Found </h3>";
?>
<br><br>
<div class="container">
<div class="row">
<?php
while ($row = mysqli_fetch_assoc($res)) {
?>
<div class="col item_col">
<?php echo $row["img_id"] . "<br>" . $row["product_id"] ."<br>". "<img src ='".$row["image_path1"]."' width=100px height=100px data-src1='".$row['image_path1']."' data-src2='".$row['image_path2']."'>"; ?>
</div>
<?php
}
?>
</div>
</div>
<?php
include('dbclose.php');
?>
jquery
<script type="text/javascript">
$(document).ready(function () {
$(".imgs").each(function(i,el){
$(this).mouseenter(function(){
$(this).attr("src",$(this).attr("data-src2"))
}).mouseleave(function(){
$(this).attr("src",$(this).attr("data-src1"))
})
})
});
</script>

Comments show in last post in codeigniter

Check my image all comment show in one post i am pass post_id 53 56 here is 53 comment and 56 comment you see but it show 53 comment in 56 post i have post and comments system like facebook but my problem is that all comments show in last post. please check it my code i have try many method but it's not working if you have any good solution soo please help me
Controller
public function commentlist(){
$conn = mysqli_connect("localhost","root","","finance");
$memberId = 1;
$sql = "SELECT * FROM tbl_comment INNER JOIN signup ON tbl_comment.u_id = signup.id";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
}
public function commentadd(){
$conn = mysqli_connect("localhost","root","","finance");
$u_id = $this->session->userdata('log_in')['id'];
$u_image = $this->session->userdata('log_in')['image'];
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$postID = isset($_POST['tmp']) ? $_POST['tmp'] : "";
$name = array();
$name[0] = $this->session->userdata('log_in')['f_name'];
$name[1] = $this->session->userdata('log_in')['l_name'];
$commentSenderName = implode(" ", $name);
$sql = "INSERT INTO tbl_comment(post_id, parent_comment_id,u_id,u_image,comment,comment_sender_name,date) VALUES ('" . $postID . "','" . $commentId . "','" . $u_id . "','" . $u_image . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
}
this is my view file
View
<form id="frm-comment_<?php echo $id;?>">
<div class="input-row_<?php echo $id;?>">
<?php if($this->session->userdata('log_in')['image'] !=NULL ): ?>
<img src="<?php echo base_url(); ?>uploads/<?php echo $this->session->userdata('log_in')['image'];?>" style="height:42px; width:42px;" class="img-circle">
<?php else : ?><img src="<?php echo base_url('assets/images/generic-avatar.jpg'); ?>" style="height:42px; width:42px;" class="img-circle">
<?php endif; ?>
<input type="hidden" name="comment_id" id="commentId_<?php echo $id; ?>"/>
<input type="hidden" name="tmp" id="tmp" value="<?php echo $id;?>" />
<input class="input-field" type="text" name="comment" id="comment_<?php echo $id; ?>" placeholder="Write a Comment..">
</div>
<input type="button" class="btn-submit" id="submitButton_<?php echo $id;?>" value="Comment" >
<div id="comment-message_<?php echo $id;?>" style='display: none;'>Comments Added Successfully!</div>
<div class="output_<?php echo $id?>" ></div>
</form>
</div>
</div>
</div>
</div>
Script
<script>
$( "#com_<?php echo $id; ?>" ).click(function() {
$("#comment_<?php echo $id;?>").focus();
});
function postReply(commentId) {
$('#commentId_<?php echo $id; ?>').val(commentId);
$("#comment_<?php echo $id; ?>").focus();
}
$(document).ready(function () {
listComment();
});
$("#submitButton_<?php echo $id;?>").click(function () {
$("#comment-message_<?php echo $id;?>").css('display', 'none');
var str = $("#frm-comment_<?php echo $id;?>").serialize();
$.ajax({
url: "<?php echo base_url();?>finance/commentadd",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message_<?php echo $id;?>").css('display', 'inline-block');
$("#comment_<?php echo $id; ?>").val("");
$("#commentId_<?php echo $id; ?>").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
function listComment(){
$.post("<?php echo base_url();?>finance/commentlist",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
var post_id = data[i]['post_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{comments = " \ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\<div class='comment-text'>\ <span>" + data[i]['post_id'] + "</span><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
<a class='btn-reply' style='font-size:14px;' onClick='postReply(" + commentId + ")'> Reply</a>\
<span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$(".output_<?php echo $id?>").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "\ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\
<div class='comment-text'> <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
\ <span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
</script>
<?php }?>
I think your code is complex because there is not need to save user image ,name in comment table ,you need to use only comment id(auto increment) post id, user id , comment.
Yo get all comments for particular post you should fetch by post ir for that post.
Example :- when user click on particular post , suppose its post id is 1 then as click click on this you have to pass a request with this post id to comment table where query will match this post id in comment id if this condition true then redirect page to view with all comment and show them.
Controller
Query:- $this->model_name->function_name($id);
In model
$this->db->where('post_id', $id);
$this->db->get('comment_table')->result_array();
This query will fetch all comment for clicked post.

Updating Database and Page Content at the Same Time

This is a tough one for me. a total of five documents involved in this process. I can't help but feel that I am over complicating this issue. I asked about this previously and THOUGHT I understood the issue, but then I tried to add a simple "loading" modal to the equation, and it broke. What's worse I can't get it working anymore. I have changed too much. Yes I know I should have backed it up, let's get past that. The one language I cannot change at all in this whole element is my DB language, which is MySql.
What I Want to Happen
Page loads all non-archived submissions. The data is structured so that some but not all data is displayed for each row. At least not until the user clicks the "more info" button. NOTE: THIS IS NOT THE PROBLEM BUT ONLY HERE BECAUSE I HAVEN'T BUILT THIS YET, I WILL FOCUS ON THIS LATER.
After the user has finished using the data from one row, I would like the user to be able to archive the data into the database by changing the "archived" field from 0 to 1. After that is accomplished, I would like the row to disappear. If there is a lag and more than a second or two is needed to accomplish this, then a loading modal should appear that will indicate that the page has received the request and prevents the user from pressing the "archive" button multiple times.
What is Happening Now
When the page loads, all non-archived data is displayed in rows that show some but not all information for each record in a table. When the user clicks the "more info" button nothing happens. Note: Again I am not focusing on this issue I know how to fix this. When the user clicks on the "archive" button, it does nothing, but if they click if multiple times it eventually will bring up the "loading" modal and then refresh the page. The row that should have disappeared is still there, and the record still shows a "0" instead of a "1" as it should.
Final Comments Before Code Is Given
I am open to using other languages as I am a fast learner, I just don't know how to integrate them. But if you do respond with that, please also explain why my way is inferior and what I would have to do to make this work. I am still learning AJAX (very much beginner) and PHP (intermediate . . . I think).
The Code
index.php - abridged without head
<div class="container">
<h1><span class="hidden">Locate My Pet</span></h1>
<h2>Administration</h2>
<p class="lead alert alert-info">Hello There! You can review and archive submitted requests here.</p>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="text-center">Submissions</h2>
</div><!--/.panel-heading-->
<div id="results"></div><!--To be populated by script-->
</div><!--/.panel .panel-default-->
</div><!-- /.container -->
<footer class="footer">
<div class="container">
<p class="text-muted text-center">© 2016 TL Web Development and Design</p>
</div><!--/.container-->
</footer><!--/.footer-->
<div class="modal fade" id="archiveMessage" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Archiving Submission</h4>
</div><!--/.modal-header-->
<div class="modal-body">
<p>Please wait . . .</p>
</div><!--/.modal-body-->
</div><!--/.modal-content-->
</div><!--/.modal-dialog-->
</div><!--/.modal-->
submission.php
<table class="table table-responsive table-striped">
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>Contact</th>
<th>Pet Info</th>
<th>Tools</th>
</tr>
<?php
require "../_php/connect.php";
$get_all = "SELECT request_id, fName, lName, address, city, state, zip, pPhone, cPhone, email, pName, gender, spayedNeutered, howLost, comments, timeEntered, archived FROM requests";
$result = $conn->query($get_all);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if (!$row['archived']) {
echo "<tr id='" . $row['request_id'] . "' class='fade in'>
<td>
" . $row['fName'] . " " . $row['lName'] . "</br>
<strong>Sent: </strong>" . $row['timeEntered'] . "
</td>
<td>" . $row['address'] . "</br>" . $row['city'] . " " . $row['state'] . ", " . $row['zip'] ."</td>
<td>
<strong>Primary Phone:</strong> <a href='tel:" . $row['pPhone'] . "'>" . $row['pPhone'] ."</a></br>
<strong>Cell Phone:</strong> <a href='tel:" . $row['cPhone'] . "'> " . $row['cPhone'] . "</a></br>
<strong>Email:</strong> <a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>
<td>
<strong>Pet Name:</strong> " . $row['pName'] . "</br>
<strong>Gender:</strong> " . $row['gender'] . "</br>
<strong>Spayed or Neutered?:</strong> ";
if ($row['spayedNeutered'] = 0) {
echo "No</td>";
} else {
echo "Yes</td>";
}
echo "<td>
<button class='btn btn-info'>More info</button></br>
<form action='../_php/archive.php' method='get'><input type='hidden' value='" . $row['request_id'] . "' id='row_id'><button type='submit' class='btn btn-warning archive'>Archive</button></form>
</td>
</tr>";
}
}
} else if ($conn->connect_error != NULL) {
echo "<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>";
} else {
echo "<tr><td colspan='5'><div class='alert alert-info' role='alert'>No Records were found.</div></td></tr>";
}
?>
<script type="text/javascript" src="../_js/query.js"></script>
</table>
connect.php - some content no included for security reasons
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>)");
}
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$(".archive").click(function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
});
});
});
functions.php
<?php
require "connect.php"; // Connect to database
function archive($id) {
require "connect.php";
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['callArchive'])) {
archive($_POST['callArchive']);
} else {
archive(1);
}
?>
Since archive button is dynamically loaded, its the best choice to use .on('click') rather than .click() that does not fires on a dynamically loaded element. Try to read the question and answeres here, specially the selected correct answer.
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$("#results .archive").on("click",function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
//If you dont want to change your functions.php file use the commented line below instead of the above code
//data: {'callArchive':id},
});
});
});
When the user clicks on the "archive" button, it does nothing, but if
they click if multiple times it eventually will bring up the "loading"
modal and then refresh the page. The row that should have disappeared
is still there, and the record still shows a "0" instead of a "1" as
it should.
Since your ajax call data contains post 'archive' in which the value is id and you want to update some data of your request table but you are checking the wrong index of the POST data(if (isset($_POST['callArchive'])) ) rather change it to if (isset($_POST['callArchive']))
<?php
function archive($id) {
require "connect.php";// Connect to database
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['archive'])) {
archive($_POST['archive']);
} else {
archive(1);
}
?>
Hope that helps :D

Using Ajax to get and show mysqli query results

I'm practicing Ajax by making an app that checks the content of a database table and inserts it into my page asynchronously, only the first row of the table is printing and I'm not sure why. This is my code:
index.php - Here is where I create the page with an empty space in #result_table that should get filled by the table fetched by places.php
<div class="row">
<div class="col-xs-3">
<button type="button" class="btn btn-lg btn-default" id="showPlaces" name="showPlaces">Mesas</button>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<thead>
<tr>
<th>Nombre</th><th>Piso</th><th>Cliente</th><th>Mesero</th><th>Area</th><th>Estado</th>
</tr>
</thead>
<tbody id="result_table">
</tbody>
</table>
</div>
</div>
places.php - Here I make the query and return(?) the data
<?php
include("con.php");
mysqli_select_db("unicentaopos", $c);
$result = mysqli_query($c,"SELECT * FROM places");
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['FLOOR']."</td>";
echo "<td>". $places ['CUSTOMER']."</td>";
if (!$places['WAITER']) {
echo "<td>" . "VACIO" . "</td>";
} else {
echo "<td>". $places ['WAITER']."</td>";
}
echo "<td>". $places ['AREA']."</td>";
echo "<td>". $places ['ESTADO']."</td>";
echo "</tr>";
}
mysqli_free_result($result);
?>
script.js - Here I use jQuery to make the Http request
$( document ).ready(function() {
$('#showPlaces').click(function(){
$.ajax({
type:'GET',
url: 'places.php',
dataType: 'html',
success: function(result){
$('#result_table').html(result);
} // End of success function of ajax form
}); // End of ajax call
});
});
con.php - Here I connect to the database
<?php
$c = mysqli_connect("localhost","root","root","unicentaopos");// Check connection
if (mysqli_connect_errno()) { // Si hay error lo menciona en alerta.
echo '<div class="alert alert-danger">';
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
echo '</div>';
} else { // Si no hay error.
}
?>
I've been stuck on this for a while, could you guys help me pinpoint the problem? I guess it's either the way i'm returning the data from places.php, or I'm making a mistake in the connection, wich would be weird since that very same code worked for a simple example I did a while ago.
Please remember, I'm new to Ajax so anything you can tell me that helps me improve will be very welcome.
Fixed it with help of the comments and edited the post with the working code.

Looping through a jQuery statement

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.

Categories