I have a link that sends a query string to a PHP file that returns data from a Mysql server as JSON. I want to put this JSON data into a DIV that has an ID which matches the query string sent to the PHP file.
Here is my PHP generated Link and DIV
<html>
<head>
<title>BadNoise</title>
</head>
<body>
<form action="Artisttest.php" method="post">
<fieldset>
<p> <input type="submit" value=" Search Our Artists" /> </p>
</fieldset>
</form>
<?php
$con=mysqli_connect("localhost","ee2800","secret","ee2800");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
$result = mysqli_query($con,"SELECT * FROM artist LIMIT 10");
if($_SERVER["REQUEST_METHOD"] == "POST")
echo " <h2>List of BadNoise Artists</h2>
<table border='0'>
<tr>
<th>Artist Number</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Search Songs</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ArtistNumber'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo '<td> <a class="dynamic" href="test4.php?name='. urlencode($row['ArtistNumber']).'">Search Songs</a></td>';
echo "<td><div id=" . $row['ArtistNumber'] . "></div></td>";
echo "</tr>";
}
echo "</table>";
$results->close();
mysqli_close($con);
?>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="general.js"></script>
</body>
Here is the PHP file that returns the JSON data
<?php
$row = $_GET['name'];
echo $_GET['name'];
$dbs = new mysqli("localhost", "ee2800", "secret", "ee2800");
$results = $dbs->query("SELECT * FROM songs WHERE ArtistNumber = {$_GET['name']};");
$rows = array();
while ($r = mysqli_fetch_array($results))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
And here is my attempt at doing this asynchronously with JS.
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
I think I am on the right path but am having trouble targeting the DIV.
Is this what you meant?
</tr><tr><td>1</td><td>Steve</td><td>Perry</td><td> <a id="dynamic" href="test4.php?name=1">Search Songs</a></td></tr><td><div id=1></div></td>
Since you're adding the content on the same row where the click originated, you may not need the id of the div in order to add the content there. Using the link that was clicked determine the parent tr using .closest() the drill down to the div using .find() and .last().
And since you're likely to have multiple links I would recommend using a class .dynamic instead of an id. <td> <a class="dynamic" href="test4 ....
This should do it:
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
UPDATE
The above code has been edited to include DOM ready.
Concept verification --> with DOM ready clicking a a.dynamic link does not navigate to the link.
Related
I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>
I am trying to utilize a button that will open a dialog based on the specific row that the button is located in. I have attached my code below.
The button is class is dlg-outletpart-btn:
Here is the jquery javascript portion:
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
} );
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
$( ".dlg-outletpart-btn" ).click(function() {
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
Here is the html with php:
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
$q = $protoFM['EMGSV'] -> newFindCommand('web_outlets');
$q -> addFindCriterion('id_account', '=='.$id_account);
$r = $q->execute();
if(FileMaker::isError($r)){
if($r->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$r->code;
}
}else{
}
} else {
echo "You are not logged in.";
}
?>
<?php
foreach ($r->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($r->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>
I didn't try to test this and there was a lot of cleanup needed so take this with a grain of salt rather than the exact solution.
Before I get into the explanation, there are a couple of points that need to be made:
Stay on top of your indention levels
Poorly indented code is harder to build in and even harder to troubleshoot.
REMEMBER: what you post online reflects on you as a programmer.
Don't use variables with single letters.
Give your variables proper and descriptive names. Single letter names also make it hard to code and hard to troubleshoot.
If you don't need it, don't write it
This is especially true if you're going to post on StackOverflow asking for help. The place where you had an else clause without any code in it should be stripped out of your question and really should be stripped out of your code. If you don't have any tasks to perform within a clause then don't add it. Add it back in when you actually need it. This goes for the closing and immediately opening of the php element. There's no reason to close one php element if you're going to immediately open another. If this is because your knitting two different sections together for the question then clean it out before you submit it.
So, here's the code you can try. Focus on the parts that I commented on in the javascript. The basic idea is:
Make the table your main selector.
You could make the tr element the main selector and it would still give you the index of the tr in the table, but adding the selector to the table itself means if you programmatically add new rows after the DOM has been rendered the jquery method will work for them as well.
Use the this keyword as a starting point.
this will be the button clicked which will allow you to navigate around.
Leverage jquery's navigation methods, in this case closest().
<html>
<head>
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
});
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
// I changed the element selector to the id of the table element.
// This allows you to specify the selector for the 'on' method to apply to all
// tr elements within the given table and then reference their index relative
// to the overall table.
// I'm using `button` for the method's selector because you have only have
// on button in your table so it de-couples your selector from your class name.
$( "#table_id_outlets" ).on('click', 'button', function() {
debugger;
// this: refers to the button that was clicked
// closest: walks up the node hierarchy till it finds a `tr`
// index(): gives you the index of the `tr` within the table.
// Use the index number however you need.
console.log($(this).closest('tr').index());
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
</head>
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
// Note: you can't put a space between your
$query = $protoFM['EMGSV']->newFindCommand('web_outlets');
$query->addFindCriterion('id_account', '==' . $id_account);
$result = $query->execute();
if(FileMaker::isError($result)){
if($result->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$result->code;
}
}
} else {
echo "You are not logged in.";
}
foreach ($result->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
// Use an unordered list here
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>
</html>
I didn't test the php portion out, but the jquery definitely works.
I have a PHP generated table from a postgres query. How can I insert an index column with numbered rows at the beginning of the table using tablesorter plugin? The sorting works. Thank you.
klejgkekrj
qwef
<html>
<head>
<link href="/media/css/blue/style.css" rel="stylesheet">
<script src="/media/js/jquery.js" type="text/javascript"></script>
<script src="/media/js/jquery.tablesorter.js" type="text/javascript"></script>
<script src="/media/js/jquery.tablesorter.widgets.js" type="text/javascript"> </script>
<script src="/media/js/jquery.tablesorter.pager.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#tabel").tablesorter({ widgets: [ 'zebra' , 'filter' ] })
});
</script>
</head>
<body>
<?php
$con = pg_connect("user=* password=* host=localhost port=5432 dbname=users ") or die (pg_last_error());
$query = "SELECT * from users";
$result = pg_query($con, $query);
echo "<table id=\"tabel\" class=\"tablesorter\">
<thead>
<tr>";
//next code get column names
for($i=0; $i < pg_num_fields($result); $i++){
$field_info = pg_field_name($result, $i);
echo "<th> $field_info </th>";
}
echo "
</tr>
</thead>";
//next code fetch cells content
echo "<tbody>";
while ($row=pg_fetch_row($result)){
echo "<tr>";
foreach($row as $_column){
echo "<td> $_column </td>";
}
echo "</tr>";
}
echo "</tbody>
</table>";
pg_close($con);
?>
</body>
</html>
I'm not that great with php, but couldn't you just do this?
echo "<table id=\"tabel\" class=\"tablesorter\">
<thead>
<tr>
<th>#</th>";
.
.
.
//next code fetch cells content
echo "<tbody>";
$i=1;
while ($row=pg_fetch_row($result)){
echo "<tr>";
echo "<td> $i </td>";
$i++;
foreach($row as $_column){
echo "<td> $_column </td>";
}
echo "</tr>";
}
If you want a that column to not sort and stay unchanged, you can use the following widget (demo) with header option to prevent sorting:
// target the number column using a zero-based index
var number_column = 0;
// add custom numbering widget
$.tablesorter.addWidget({
id: "numbering",
format: function(table) {
var c = table.config;
$("tr:visible", table.tBodies[0]).each(function(i) {
$(this).find('td').eq(number_column).text(i + 1);
});
}
});
$("table").tablesorter({
theme: 'blue',
// prevent first column from being sortable
headers: {
0: { sorter: false }
},
// apply custom widget
widgets: ['numbering']
});
I've the code to initialize the modal-box:
<script>
var grid_modal_options = {
height: 'auto',
width: '80%',
modal: true
};
function showProductsModalBox() {
$("#products_modal_box").dialog(grid_modal_options);
$("#products_modal_box").parent().appendTo('form:first');
}
</script>
<div id="products_modal_box" title="Products" style="display: none;">
<div class="in">
<div class="grid-12-12">
<form id="products_modal_box_form" action="#" method="post">
<table>
<thead>
<tr>
<th> </th>
<th>Product</th>
</tr>
</thead>
<!-- Query for read mysql goes here (I skipped this line because it's not the main thing I'm gonna ask since it's run well) /-->
<tbody>
<?php
//read the results
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a href='#'>Choose</a></td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
And:
<input type='text' id='products_id_textbox' name='products_id_textbox' />
<a href='#' onclick='showProductsModalBox(); return false;'>Choose products</a>
The code succeeds to show the modal box. But how to return the "Product" chosen by the user to the textbox "products_id_textbox"? Thanks.
add inline javascript:
<?php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td>Choose</td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
Instead using inline JS, you can write so (or something like this);
// php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a rel='dialog' data-id='{$fetch[0]}'>Choose</a></td>";
print " <td>{$fetch[0]}</td>";
print "</tr>";
}
// js
$(document).ready(function(){
...
$("a[rel=dialog]").each(function(){
var id = this.getAttribute("data-id");
$('#products_id_textbox').val(id);
$('#products_modal_box').dialog('close');
});
I seem to be having a problem inserting a <div> element in the correct area. I want to push a button, in this case "more info" and display more information under the first div area using jquery.
example:
<div id="Main-info">
<div id="more-info">
</div>
</div>
The problem I'm having is the "Main-info" area is calling a php script and grabbing info from the database and displaying it in a table. The second php file I have loads in the "more-info" div so when I push the more info button the second php files goes under the entire first div but i want it to go under the specific information that I click.
A better example of what I am trying to accomplish is like the wefollow.com site, where you push the more info button and more info display right under the info you click. In my case the additional info goes under the entire table at the buttom.
Here is the code:
index.php:
<?php
include("buy.functions.php");
?>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="listing.js"></script>
<div id="article-area">
<h1>Welcome</h1>
<div id="output-listings">
<div id="more-information">
</div>
<?php outputListingsTable(); ?>
</div><!--end output-listings-->
buy.functions.php:
<?php
function outputListingsTable()
{
$mysql = new mysqli('localhost', 'root', 'root', 'ajax_demo') or die('you\'re dead');
$result = $mysql->query("SELECT * FROM explore") or die($mysql->error);
if($result)
{
echo "<table> \n";
while($row = $result->fetch_object())
{
$id = $row->id;
$siteName = $row->site_name;
$siteDescription = $row->site_description;
$siteURL = $row->site_url;
$sitePrice = $row->site_price;
echo "<div id=\"" . $id . "\"> \n";
echo " <tr> \n";
echo " <td>" . $siteName . "</td> \n";
echo " <td>" . $siteURL . "</td> \n";
echo " <td><a id=\"" . $id . "\" class=\"more-info\" href=\"#\">More info</a></td> \n";
echo " </tr> \n";
echo "</div> \n";
}
echo "</table> \n";
}
}
?>
getinfo.php:
<?php
function outputDescriptionTable($id)
{
$mysql = new mysqli('localhost', 'root', 'root', 'ajax_demo') or die('you\'re dead');
$result = $mysql->query("SELECT * FROM explore WHERE id=" . $id) or die($mysql->error);
if($result)
{
echo "<table> \n";
while($row = $result->fetch_object())
{
$siteName = $row->site_name;
$siteDescription = $row->site_description;
$siteURL = $row->site_url;
$sitePrice = $row->site_price;
echo "<div id=\"more-information\"> \n";
echo " <tr> \n";
echo " <td>" . $siteDescription . "</td> \n";
echo " <td>" . $sitePrice . "</td> \n";
echo " </tr> \n";
echo "</div> \n";
}
echo "</table> \n";
}
}
?>
<?php $id = $_GET['id']; ?>
<?php outputDescriptionTable("$id"); ?>
listing.js:
$(function(){
$("tr").hover(function(){
$(this).addClass("hover");
}, function() {
$(this).removeClass("hover");
});
$('.more-info').click(function() {
$('#more-information').show().load('getinfo.php?id=' + $(this).attr('id'));
return false;
});
});
jQuery's closest should solve your problem. Something like:
$('.more-info').click(function(e) {
$(e.target).closest('.more-information').show().load('getinfo.php?id=' + $(this).attr('id'));
return false;
});
From the doc:
Closest works by first looking at the
current element to see if it matches
the specified expression, if so it
just returns the element itself. If it
doesn't match then it will continue to
traverse up the document, parent by
parent, until an element is found that
matches the specified expression. If
no matching element is found then none
will be returned.
Also, your 'more-information' divs should have the class more-information, as opposed to the ID, as IDs should be unique, else strange things might happen.