Show alert with the content of a Database selection - php

I am very new to JavaScript what is related to it.
I have a set of dynamic rows and corresponding columns to those rows. In one column I have a button. When I click on it, it displays the results of a select query in another page based on the Posted Competence_ID.
The query works fine and I get correct results when I click on the button. However, what I would like to do now, is to display that message in an alert when the button is clicked and stay on the same page rather than opening a new tab..
Here is the relevant HTML code that shows the table I use:
echo "<table border='1' id='mycompstable' class='sortablee' cellpadding='0' cellspacing='0'>";
echo "<tr><th>ID</th><th>Competence Group</th><th>Competence Class</th><th>Competence Description</th><th>Own Evaluation</th><th>Manager's evaluation from last year</th><th>Target levels</th><th>Gap</th><th>Action</th><th class='unsortable'>Action ready target </th></tr>";
foreach($descs as $compi){
echo "<tr>";
echo "<td>".$compi['Competence_ID']."</td>";
echo "<td><p style='text-align: center;'>".$compi['Competence_Group']."</p></td>";
if(isset($compi['Competence_class'])){echo "<td>".$compi['Competence_class']."</td>";}else echo "<td><p style='text-align: center;'>-</p></td>";
echo "<td>".$compi['Competence_Description']."</td>";
echo "<td class='evaluation'>";
echo "<select class='ownlevelselect' id='ownlevelselect-.".$compi['Competence_ID']."' name='level-".$compi['Competence_ID']."' >";
if (isset($compi['ownlevel']) && $compi['ownlevel']!= '' && !empty($compi['ownlevel']) && $compi['ownlevel']!= 0) {
echo "<option selected value='".$compi['ownlevel']."' selected='selected'>".$compi['ownlevel']."</option>";
}
echo "<option value='' >--</option>";
echo "<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option>";
echo "</select>";
echo $compi['ownlevel'];
echo '<a test="'.$compi['Competence_ID'].'" onClick="showLevels('.$compi['Competence_ID'].');" target="_blank" href="'.INDEX.'?categ='.$_GET['categ'].'&action='.$_GET['action'].'&subaction=viewlevels'.'&levels='.$compi['Competence_ID'].'">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
echo "</td>";
Here is the code to retrieve the data:
function fetchlevels($Competence_id){
$this->query="SELECT * FROM levels WHERE comp_id=".$_REQUEST['levels'];
$tulos=$this->suoritaKysely();
return $tulos;
}
And here is the page that I want to show in the message:
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
echo '<input type="button" value="close" window onclick="window.close();">';
?>
Any kind of help would be very much appreciated

Here is a Ajax simulation in jsfiddle
http://jsfiddle.net/ncubica/Umxjb/
HTML
<i style='display:none' id="loadingPopup">Loading</i>
<table>
<tr>
<td data-id="td1"> row 1</td>
</tr>
<tr>
<td data-id="td2"> row 2</td>
</tr>
<tr>
<td data-id="td3"> row 3</td>
</tr>
</table>
javascript
$("table").on("click", function(event){
var $target = $(event.target);
if($target.is("td")){
var id = $target.attr("data-id");
makeAjax(id);
}
});
//simulating ajax
function makeAjax(id){
//you will have to use ajax an retrieve you json format
//i will simulate ajax only
$("#loadingPopup").show();
var _json = { id : id, value : "some value", description : "some description"};
setTimeout(function(){response(_json)}, 1000);
}
function response(_json){
$("#loadingPopup").hide();
alert(_json.id + " - " + _json.value);
}
CSS
table{font-family:arial; font-size:12px; width:100%}
table tr td{border-bottom:1px solid #CCC; padding:10px;}

Just an example based on the given info!
echo '<a onClick="showLevels('.$compi['Competence_ID'].');">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
Javascript/jQuery/Ajax
function showLevels(comp_id)
{
$.ajax({
type: "GET",
url: "process_file.php?comp_id="+comp_id,
success: function (result) {
alert(result);
}
});
}
process_file.php
<?php
//Your database Config.
$comp_id=$_REQUEST['comp_id'];
$this->query="SELECT * FROM levels WHERE comp_id=".$comp_id;
$tulos=$this->suoritaKysely();
//Proper Output Actions
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
?>

Related

Submitting looped values to database, one by one using ajax

Am developing results management system where a lecturer can login and update students' results.
The system exacts all students offering that course unit and the lecturer updates the marks.
I discovered that it is very monotonous for a lecturer to click a button to submit results for each student yet they are very many students and very many buttons appearing on every student extracted, Then i thought of using AJAX to submit results on "ONCHANGE call event".
The simple AJAX script is working well only that , it is picking the last student in the loop and stores results in line with his id even if you try storing results for other students. It will just update results for the last students.
Here is my code for the looped students.
Marks.php
<?php
$row=mysql_fetch_assoc($sql);//course unit information
if(mysql_num_rows(mysql_query("SELECT * FROM allocations WHERE courseunitid='".$row['courseunitid']."' AND acid='".$_POST['acid']."' AND semester='".$_POST['semester']."' AND adminid='".$_SESSION['adminid']."'"))<1){
echo "<b><i><font color=red>Sorry! This course unit was not allocated to you in the specified search</font></i></b>";
}else{
echo"<hr size=1>";
echo "<table>
<tr>
<td colspan=4><b>UPDATE RESULTS OF BELOW STUDENTS</b></td>
</tr>
<tr>
<td><b>NO</b></td>
<td><b>REG NO</b></td>
<td><b>NAME</b></td>
<td><b>TEST</b></td>
<td><b>EXAMS</b></td>
</tr>
";
$x=1;
$sql_results=mysql_query("SELECT students.*,results.* FROM results INNER JOIN students ON results.stid=students.stid WHERE results.courseunitid='".$row['courseunitid']."' AND results.acid='".$_POST['acid']."' AND results.regsem='".$_POST['semester']."' AND results.adminid='".$_SESSION['adminid']."'");
while($rows=mysql_fetch_assoc($sql_results)){
?>
<tr><td><?php echo $x++?> . </td><td> <?php echo strtoupper($rows['regno']) ?></td><td><?php echo ucwords($rows['fname']).' '.ucwords($rows['mname']).' '.ucwords($rows['lname']) ?></td><td><input type='text' name='test' value='<?php echo $rows['test'] ?>' style='width:40px;height:26px' maxlength='2' onblur='enter_results("test",this.value)'></td><td><input type='text' maxlength='3' name='exams' value='<?php echo $rows['exams']?> ' style='width:40px;height:26px' onblur='enter_results("exams",this.value)'></td><td id='<?php echo $rows['stid']?>'><?php echo $rows['stid'] ?></td></tr>
<script>
//Ajax Script for picking values (Marks)
function enter_results(marksname,marksvalue){
if(marksname=='test'){
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML="<font color=green><i>Saving test marks...</i></font>";
}else{
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML="<font color=green><i>Saving exam marks...</i></font>";
}
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4 && xhttp.status==200){
if(marksname=='test' || marksname=='exams' ){
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML=xhttp.responseText;
}
}
}
xhttp.open('GET','../ajax_calls/ajax_call.php?marksname='+marksname+'&marksvalue='+marksvalue+'&rid=<?php echo $rows['rid']?>',true);
xhttp.send();
}
</script>
<?php
}
echo "</table>";
?>
1st : Your creating multiple javascript function inside the while loop it was wrong approach . you need to create single function and call with dynamic parameter .
onblur='enter_results("test",this.value,"<?php echo $rows[\'stid\'] ?>","<?php echo $rows[\'rid\'] ?>")'>
Note: Added student id and row id as third and fourth parameter in function call .
PHP :
<hr size=1>
<table>
<tr>
<td colspan=4><b>UPDATE RESULTS OF BELOW STUDENTS</b></td>
</tr>
<tr>
<td><b>NO</b></td>
<td><b>REG NO</b></td>
<td><b>NAME</b></td>
<td><b>TEST</b></td>
<td><b>EXAMS</b></td>
</tr>
<?php
$x=1;
?>
//while loop start here
<tr>
<td><?php echo $x++?> . </td>
<td> <?php echo strtoupper($rows['regno']) ?></td>
<td><?php echo ucwords($rows['fname']).' '.ucwords($rows['mname']).' '.ucwords($rows['lname']) ?></td>
<td><input type='text' name='test' value='<?php echo $rows['test'] ?>' style='width:40px;height:26px' maxlength='2' onblur='enter_results("test",this.value,"<?php echo $rows[\'stid\'] ?>","<?php echo $rows[\'rid\'] ?>")'></td>
<td><input type='text' maxlength='3' name='exams' value='<?php echo $rows['exams']?> ' style='width:40px;height:26px' onblur='enter_results("exams",this.value)'></td>
<td id='<?php echo $rows['stid']?>'><?php echo $rows['stid'] ?></td>
</tr>
//while loop end here
</table>
Javascript : Script should be outside the while loop .
<script>
//Ajax Script for picking values (Marks)
function enter_results(marksname,marksvalue,stdid,rowid){
if(marksname=='test'){
document.getElementById(stdid).innerHTML="<font color=green><i>Saving test marks...</i></font>";
}else{
document.getElementById(stdid).innerHTML="<font color=green><i>Saving exam marks...</i></font>";
}
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4 && xhttp.status==200){
if(marksname=='test' || marksname=='exams' ){
document.getElementById(stdid).innerHTML=xhttp.responseText;
}
}
}
xhttp.open('GET','../ajax_calls/ajax_call.php?marksname='+marksname+'&marksvalue='+marksvalue+'&rid='+rowid,true);
xhttp.send();
}
</script>

How to pass radio input type value from PHP while loop to HTML?

I have radio button in a PHP while-loop.
I am storing the first row value in the value of radio button.
I need to pass the value of radio button in HTML a href.
How to pass that value with both PHP and HTML in same page??
My code:
index.php
<html>
<body>
<img src="images/print_label.png" name="Image3" width="152" height="110" border="0" align="top" style="margin-top:10px">
<?php
include "db.php";
require_once "purna_insert_orders_to_ship.php";
if(isset($_POST['submit']))
{
if($_POST['value'] == 'readytoship') {
// query to get all Fitzgerald records
$query = "SELECT * FROM orders WHERE status='readytoship'";
}
elseif($_POST['value'] == 'readytodispatch') {
// query to get all Herring records
$query = "SELECT * FROM orders WHERE status='readytodispatch'";
} else {
// query to get all records
$query = "SELECT * FROM orders";
}
$sql = mysql_query($query);
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
echo "<div id='showmenu' class='scroll'>";
echo "<table id='table_struct' cellspacing='0' cellpadding='1' border='1' width='400' height='30'>
<tr class='tr_class' bgcolor='white'>
<td align='center' style='font-weight:bold'> Select </td>
<td align='center' style='font-weight:bold'> Po Id </td>
<td align='center' style='font-weight:bold'> Customer Name </td>
<td align='center' style='font-weight:bold'> quantity </td>
<td align='center' style='font-weight:bold'> price </td>
<td align='center' style='font-weight:bold'> status </td>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr height='20' data-order_id='".$row['po_id']."'>
<td align='center'><input type='radio' class='case' name='radio' value='".$row['po_id']."'></td>
<td align='center'>".$row['po_id']."</td>
<td align='center'>".$row['customer_name']."</td>
<td align='center'>".$row['quantity']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['status']."</td>
";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
}
?>
</body>
</html>
Can anyone please help me out??
To use the value in an anchor tag, you would need to invoke the GET method as follows:
Click here
But, since it is in a radio button, you might want to consider using an HTML form with submit button rather than an anchor tag.
If you want to call that value in html ahref then you should need some jquery too
First you should echo some value in your radio button
<input type="radio" name="buttonval" id="smallBtn" value="yourvalue"/>
Then in the change even of the radio button, You shall fire the event
<script type="text/javascript">
$(document).ready(function()
{
$("input[name=buttonval]").on('change', function(){
var $postID = $('input:radio[name=buttonval]:checked').val();
$postID = "="+$postID;
});
$.ajax ({
type: "GET",
url: "localhost/ajax/buttonvaluereceiver.php",
data: {"postID" : $postID }
});
});
</script>
and in the success event of the ajax call you will get the result of what buttonvaluereceiver.php file does
Update :
As you need to do instantly in radio button change I am updating my answer for you
Here is the html and script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name='frm' id='frm'>
<input type='radio' id='test' value='rad' name='rad'>
</form>
Your link :
<div id='link'></div>
<script>
$("input").change(function(){
var data = $("#frm").serialize();
Call();
});
function Call()
{
$.ajax({
type: "POST",
url : "result.php",
data : $("#frm").serialize(),
success : function(data)
{
console.log(data);
$("#link").html(data);
}
},"json");
}
</script>
Here is the php that creates your link
<?php
echo "<a href='url.php?id".$_POST['rad']."'>Click here</a>";
?>
You can change the url and values according to your need.

Unique Value For Each Button

I have two php pages. The first page queries a database and places some data into a form
The second page, grabs the data submited from the previous page and displays the data.
THE ISSUE:
On the second page, the information is displayed in a table. At the end of each row, there is a "information" button that allows the user to click and see more details related to the data in that particular column. For some reason, the information button for every record in the table is holding the value of the first record returned in the database query. In other words no matter what button I click on in the table, it always relates to the first record returned in the query.
I'm hoping someone can help me find a solution to linking each "information" button to each unique record. In other words If I click the info button in row one, it will display the data for the record related to row 1...etc. Here's my code.
PAGE 1
<?php
$query = mysql_query ("SELECT * from cust_data group by cabinet_number ORDER by cabinet_number ASC");
WHILE ($rows = #mysql_fetch_array($query)) {
if (($rows['account_number']=="") &&
($rows['customer_first_name']=="") &&
($rows['customer_last_name']=="") &&
($rows['company_name']=="")) {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_green.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['cabinet_number'].'" id="submit">
</form>';
} else if ($rows['cabinet_number']!=="") {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_red.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['company_name'].'" id="submit">
</form>';
}
}
}
PAGE 2:
GRABS THE DATA IN PAGE ONE AND PLACES IT IN A TABLE. WHEN THE 'INFO' BUTTON IS CLICKED, MORE INFORMATION IS DISPLAYED IN A JQUERY POPUP
db_connect();
$cabinet_number = $_GET['cabinet_number'];
$company_name = $_GET['company_name'];
$query = #mysql_query ("SELECT * FROM cust_data WHERE cabinet_number = '$cabinet_number' ");
WHILE ($rows = #mysql_fetch_array($query)) {
echo'<tr>
<td><font size="4">'; echo $rows['account_number']; echo'</font></td>
<td><font size="4">'; echo $rows['customer_first_name']; echo '</font></td>
<td><font size="4">'; echo $rows['customer_last_name']; echo '</font></td>
<td><font size="4">'; echo $rows['company_name']; echo '</font></td>
<td><font size="4">'; echo $rows['cabinet_number']; echo'</font></td>
<td><font size="4">'; echo $rows['key_tag_number']; echo'</font></td>';
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo '<td><font size="4">';
echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
{
echo '<td><font size="4">'; echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
echo '</tr>';
echo '<div class="well" style="display:none;margin:1em;" class="my_modal">';
echo '<img src="images/hdc_logo_transparent.png"><br>';
echo '<div style="height:23px; width:100%; background-color:black"> <h4><font color="#FFFFFF">',' ', 'Cabinet: ', $id, '</font></h4></div>';
echo '<p>';
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Power: ', $rows['power_circuit'];
echo '<br>';
echo'<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port1'];
if ($rows['switch_and_port2'] =="") {
echo '';
} else if ($rows['switch_and_port2'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port2'];
}
if ($rows['switch_and_port3'] =="") {
echo '';
} else if ($rows['switch_and_port3'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port3'];
}
if ($rows['switch_and_port4'] =="") {
echo '';
} else if ($rows['switch_and_port4'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port4'];
}
echo '</p>';
echo'</div></form>';
}
echo'<script>
$(document).ready(function() {
$(".my_modal_open").click(function(){
$(this).closest("tr").next(".my_modal").popup({"autoopen": true});
});
});
});
</script>
</body>
</html>';
}
The issue is that you are setting the same id attribute to all the modals (which is invalid HTML markup) and expecting the click handler on the button to figure out which one to open.
UPADTE
Another issue with your markup is that you can't have <div>s as siblings of a table row, it will produce unexpected results as browsers will attempt to fix the markup and rearrange the elements, you could place the divs inside a td or use a second loop to build them.
Now I also did some digging in your popup plugin and I must say it's not very well implemented, I would recommend you look for another one. That being said I did manage to get it working, here's what you need to do:
Set an unique id for each of the modal divs, if you have some sort of id in your database data you can use that, if not then you can set up a counter variable inside the loop:
echo '<div class="well" id="my_modal'.$rows['id'].'">';
Use the same id as the class for the button that should open the modal but add "_open" as a suffix:
echo '<input type = "image" src="images/view_details.png" height="16" width="16" class="my_modal'.rows['id'].'_open">
You can now initialize the popup plugin on your divs and it will automatically assign the open action to the corresponding button:
echo'<script>
$(document).ready(function () {
$("[id^=\'my_modal\']").each(function () {
$(this).popup();
});
});
</script>';
That should fix the modal problem, here's a working demo.
Now I also have a couple observations about your code:
You should avoid the use of inline styles and as I mentioned earlier the <font> tag should be replaced for proper CSS, I would also suggest using CSS padding/margin to add space between words instead of
This type of code:
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
can be optimized to just:
if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
echoing an empty string produces no output whatsoever and there's no need for an elseif

Set approval for admin with checkbox using php,jquery and ajax

I am working in a project where i want to show only those products to user which are selected by admin from database. Actualy i want to set the approval 1 or 0 in database when admin check or unchecked that checkbox.
jobs.php
$(document).ready(function(){
$('input.check').click(function(){
if($("input.check").is(':checked'))
{
$id = $(this).attr("id");
$.post("handle.php",{action:"checked",id:$id},function(data){
alert("Peoduct is set to display...");
});
}
else
{
alert("unchecked");
$id = $(this).attr("id");
$.post("handle.php",{action:"unchecked",id:$id},function(data){
alert("Peoduct is un-set to display...");
});
}
});
});
<?php
$dbqry = mysql_query("select * from job_category");
echo "<table width='50%', border='2'>
<tr>
<th>Catergory ID</th>
<th>Category Name</th>
<th>Remove</th>
<th>Update</th>
<th>Approval</th>
</tr>";
if($dbqry)
{
while($row = mysql_fetch_array($dbqry))
{
echo "<tr>";
echo "<td align='center'>" . $row['c_id'] . "</td>";
echo "<td align='center'>" . $row['cat_name'] ."</td>";
$cid = $row['c_id'];
$aprv = $row['approval'];
echo "<td align='center'><a href='remove.php?action=cat_remove&cid=$cid'>Remove</a></td>";
echo "<td align='center'>
<a href='Update-form.php?action=cat_update&cid=$cid'>Update</a></td>";
?>
<td align="center">
<input type='checkbox' name='approval' value='approval' id ="<? echo $cid; ?>" class="check"/>
</td>
</tr>
<?
}
echo "</table>";
echo '<br/>';
echo "<a href='add.php?action=cat_add'>Add New Category</a>";
}
else
{
die(mysql_error());
}
?>`
handle.php
`<?php
include 'include/connection.php';
$action = $_POST['action'];
$id = $_POST['id'];
//echo $action;
if($action == "checked")
{
$query = "update job_category set approval=1 where c_id=$id";
$result = mysql_query($query);
if(!$result)
{
echo die(mysql_error());
}
}
else if($action == "unchecked")
{
$query = "update job_category set approval=0 where c_id=$id";
$result = mysql_query($query);
if(!$result)
{
echo die(mysql_error());
}
}
?>`
Its working but when i refresh the page or seletc the URL and press enter then all the checked data appears unchecked even after that it does not change value of approval from 1 to 0 in database, but still it make me confuse about which items are checked or unchecked. Any suggestion will be appreciated.
modify checkbox line to show checked if approval=1 in database... try this
<input type='checkbox' name='approval' value='approval' <?php if($row["approval"]==1){ echo "checked=\"checked\"";}) ?> id ="<? echo $cid; ?>" class="check"/>
html
<input type='checkbox' name='approval' value='approval' <?php echo $row["approval"]?"checked=\"checked\"":'';?> id ="<? echo $cid; ?>" class="check"/>
then add js
$(function(){
$('input[type=checkbox]').each(function(){
if($(this).attr('checked') && $(this).attr('checked')=='checked'){
$(this).attr('checked', true);
}else{
$(this).attr('checked', false);
}
})
})
and
if($("input.check").is(':checked'))
to
if($(this).is(':checked'))

onmouseover showing same data over all rows in table

im having trouble getting a popup using javascript to show table data onmouseover when mousing over images returned in a table from the DB, now the problem i have isnt with actualy getting the onmouseover working (a previous question solved that) but getting the data displayed onmouseover the change for each image moused over.
the query's im using works fine and and display the correct data but on the onmouseover only ever shows the data which should only show for the first row in the table, the 2nd and subsequent rows should show different data as the query calls (which works, just doesnt show onmouseover)
keep in mind this page is included in my index.php which has all my .js and .css calls
page code:
<table border='0' cellpadding='0' cellspacing='0' class="center2">
<tr>
<td width='60'><img src="images/box_tl.png"></td>
<td style="background: url(images/box_tm.png)" align="center"><img src="images/news.png"></td>
<td width='25'><img src="images/box_tr.png"></td>
</tr>
<tr>
<td style="background: url(images/box_ml.png)"><h2>.</h2></td>
<td style="background: url(images/box_mm.png)">
<?php
include 'connect.php';
$query = mysql_query("SELECT * FROM tbl_img") or die(mysql_error());;
echo "<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Mob Name</th> <th>Id</th> <th>Health</th> <th>Body</th> <th>Effects</th> <th>Spawn</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query )) {
$mob_id = $row['mob_id'];
$mob = $row['mob'];
$body = $row['body'];
$mob_name = $row['mob_name'];
$health = $row['health'];
$level = $row['level'];
// Print out the contents of each row into a table
echo "<tr><td>";
echo "<img src='/testarea/include/mobs/$mob' />";
echo "</td><td>";
echo $mob_name;
echo "</td><td>";
echo $level;
echo "</td><td>";
echo $health;
echo "</td><td>";
echo "
<a onmouseover='ShowPop()' href=''><img src='/testarea/include/mobs/dead/$body' /></a>
";
echo "
<div id='hidden-table' style='display:none;'>
<table border='0' cellpadding='0' cellspacing='0' class='center3'>
<tr>
<td width='14'><img src='images/info_tl.png'></td>
<td style='background: url(images/info_tm.png)' align='center'></td>
<td width='14'><img src='images/info_tr.png'></td>
</tr>
<tr>
<td style='background: url(images/info_ml.png)'><h2>.</h2></td>
<td style='background: url(images/info_mm.png)'>
";
$query2 = mysql_query("SELECT * FROM tbl_drop WHERE mob_name='$mob_name'") or die(mysql_error());
echo "<table border='0' cellpadding='1' cellspacing='1' width='250' id='2' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Item Name</th> <th>Qty</th></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query2 )) {
$id = $row['id'];
$item_img = $row['item_img'];
$qty = $row['qty'];
$item_name = $row['item_name'];
// Print out the contents of each row into a table
echo "<tr><td width='50'>";
echo "<img src='/testarea/item/$item_img' />";
echo "</td><td width='150'>";
echo $item_name;
echo "</td><td width='50'>";
echo $qty;
echo "</td></tr>";
}
echo "</tbody></table>";
echo "
</td>
<td style='background: url(images/info_mr.png)'><h2>.</h2></td>
</tr>
<tr>
<td width='14'><img src='images/info_bl.png'></td>
<td style='background: url(images/info_bm.png)' align='center'><h2>.</h2></td>
<td width='14'><img src='images/info_br.png'></td>
</tr>
</table>
</div>"
;
echo "</td><td>";
echo "test";
echo "</td><td>";
echo "test";
echo "</td></tr>";
}
echo "</tbody></table>";
?>
</td>
<td style="background: url(images/box_mr.png)"><h2>.</h2></td>
</tr>
<tr>
<td width='60'><img src="images/box_bl.png"></td>
<td style="background: url(images/box_bm.png)" align="center"><h2>.</h2></td>
<td width='25'><img src="images/box_br.png"></td>
</tr>
</table>
</html>
popup.js code:
// create the popup box - remember to give it some width in your styling
document.write('<div id="pup" style="position:abolute; display:none; z-index:200;"></div>');
var minMargin = 15; // set how much minimal space there should be (in pixels)
// between the popup and everything else (borders, mouse)
var ready = false; // we are ready when the mouse event is set up
var default_width = 200; // will be set to width from css in document.ready
function ShowPop()
{
popup($('#hidden-table').html(), 400);
}
/* Prepare popup and define the mouseover callback */
jQuery(document).ready(function(){
$('#pup').hide();
css_width = $('#pup').width();
if (css_width != 0) default_width = css_width;
// set dynamic coords when the mouse moves
$(document).mousemove(function(e){
var x,y;
x = $(document).scrollLeft() + e.clientX;
y = $(document).scrollTop() + e.clientY;
x += 10; // important: if the popup is where the mouse is, the hoverOver/hoverOut events flicker
var x_y = nudge(x,y); // avoids edge overflow
// remember: the popup is still hidden
$('#pup').css('top', x_y[1] + 'px');
$('#pup').css('left', x_y[0] + 'px');
});
ready = true;
});
/*
The actual callback:
Write message, show popup w/ custom width if necessary,
make sure it disappears on mouseout
*/
function popup(msg, width)
{
if (ready) {
// use default width if not customized here
if (typeof width === "undefined"){
width = default_width;
}
// write content and display
$('#pup').html(msg).width(width).show();
// make sure popup goes away on mouse out
// the event obj needs to be gotten from the virtual
// caller, since we use onmouseover='popup(msg)'
var t = getTarget(arguments.callee.caller.arguments[0]);
$(t).unbind('mouseout').bind('mouseout',
function(e){
$('#pup').hide().width(default_width);
}
);
}
}
/* Avoid edge overflow */
function nudge(x,y)
{
var win = $(window);
// When the mouse is too far on the right, put window to the left
var xtreme = $(document).scrollLeft() + win.width() - $('#pup').width() - minMargin;
if(x > xtreme) {
x -= $('#pup').width() + 2 * minMargin;
}
x = max(x, 0);
// When the mouse is too far down, move window up
if((y + $('#pup').height()) > (win.height() + $(document).scrollTop())) {
y -= $('#pup').height() + minMargin;
}
return [ x, y ];
}
/* custom max */
function max(a,b){
if (a>b) return a;
else return b;
}
/*
Get the target (element) of an event.
Inspired by quirksmode
*/
function getTarget(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}
All of the hidden tables have the same id, but IDs have to be unique.
provide the link as argument to ShowPop()
<a onmouseover='ShowPop(this)' ....>
then you'll be able to access the intended target inside ShowPop():
function ShowPop(o)
{
popup($(o).next('div').html(), 400);
}
Edit:
Regarding to the comment:
Currently I think the popup will not disapear onmouseout in any browser(except IE), because you didn't provide an argument to ShowPop() , what in other browsers is needed to return anything from getTarget, because they didn't know window.event.
Change this line:
var t = getTarget(arguments.callee.caller.arguments[0]);
to
var t = arguments.callee.caller.arguments[0];
...because when you take on my suggestion the link is already provided as argument to ShowPup(), there is no need to call getTarget() .

Categories