I'm creating a web page that search users in the database. When I'm typing a username in the search box, it perfectly loads results using Ajax in a table (this table is in another PHP file). But I need to select those rows when I press arrow keys or with mouse over (like Google search engine), when we are pointing to that row, it highlights. I tried with onmouseover function but no luck, but in normal PHP web pages onmouseover works. Here's what I normally used to select rows in a table.
I'll give you a very basic example, that how I use this.
<html>
<head>
<script type="text/javascript">
function f1(x){
document.getElementById(x).style.backgroundColor="#FF0000";<br/>
}
function f2(x){
document.getElementById(x).style.backgroundColor="#FFFFFF";
}
</script>
</head
<body>
<?php
echo "<table border='1'>";
echo "<tr id='tr1' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'> <td>Elephant</td></tr>";
echo "<tr id='tr2' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'><td>Snake</td></tr>";
echo "<tr id='tr3' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'><td>Spider</td></tr>";
echo "</table>";
?>
</body>
</html>
My problem is, this does not work in an Ajax loaded table. Please help me...
The mouseover event doesn't work, because you register the event before inserting the HTML.
The way around it, is by attaching an event handler to the body tag, and then looking at the original source of the element, which is basically what the jquery live method does. That would look like this:
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
I'll see if I find the time to edit this answer for the keyboard control stuff too.
Related
Hi programmers and web designers,
I am working on a small system for the company I work with and everything is almost done (thanks for this site and the help from other sites...) except for this function where I want the entire row of the table my php codes generated, for now I was only able to make my second column clickable. I already tried googling but I can't find a workable solution. FYI, I am a noob and just starting to learn php.... thanks in advance...
while($info = mysql_fetch_array( $data ))
{ echo "<tr> class='tablerows' align=center onclick=\"window.location=http://active_jobs.php?job_ticket='".$info['job_ticket']."'\">
<td>".$info['date']."</td>;
<td><a> href=somefile.php?job_ticket=".$info['job_ticket'].">".$info['job_ticket']."</td>
<td>".$info['invoice_no']."</td> <td>".$info['customer']."</td>
<td>".$info['job_type']."</td> <td>".$info['complete_date']."</td>
<td>".$info['complete_time']."</td>
<td>".$info['artist_operator_prepress']."</td>
<td>".$info['status_prepress']."</td>
<td>".$info['status_press']."</td>
<td>".$info['status_postpress']."</td> <td
width='300'>".$info['remarks']."</td>"; echo "</tr>";
} echo
"</table>";
Thanks in advance for your help.
Marco
You can’t make entire rows “clickable” using PHP. PHP is a server-side language; you generate HTML and spit it out.
If you wanted to make an entire table row clickable, you’d either have to wrap it in an <a> (invalid HTML), or use a client-side language such as JavaScript to apply an event listener, that listens for the <tr> being clicked and redirects to whatever URL you want.
You should check the generated html, you are closing the <tr> tag so the class and javascript are no longer part of it:
{ echo "<tr> class='tablerows' align=center onclick=\"window.location=http://active_jobs.php?job_ticket='".$info['job_ticket']."'\">
^ remove this and check the html again; it probably works now
You have the same mistake on the fourth line with the a tag.
For those kind of live edit in table values with php, you can go for client side scripting language javascript & jquery with ajax..
For Reference :
Live Edit table With Ajax
It's worthy...
i am answering this question by assuming that you are aware of JQUERY.Written a sample code copy it into a file '.html' and run. make sure that you are connected to internet to let jquery api to load.Thanks.
ex:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('table tr').click( function () {
alert('i am clicked');
} );
});
</script>
</head>
<body>
<table border="1">
<tr><td>1</td><td>apple</td><td>boy</td><td>jjjj</td><td>dddd</td><td></td><td>1010</td><td>1019</td><td>06-Mar-13 21:47:34</td></tr>
<tr><td>2</td><td>strawberry</td><td>girl</td><td>jjjj</td><td>dddd</td><td></td><td>1010</td><td>1019</td><td>06-Mar-13 21:47:34</td></tr>
<tr><td>2</td><td>strawberry</td><td>girl</td><td>jjjj</td><td>dddd</td><td></td><td>1010</td><td>1019</td><td>06-Mar-13 21:47:34</td></tr>
</table>
</body>
</html>
Well, you can make a table row clickable. It is very easy. You just make invisible buttons inside each table sell. Make them without borders and no colors. Then, just handle the entire row as a clickable button. You will need to do this for each TD in the row. Also, you have to have a unique id for each row so that the button can identify the row number. Something loosely like this:
<td><button type='submit' name='click_row' value='" . $info["id"] . "' style='width: 100%; background: none; border: none; box-shadow: none;'>DATA FOR THIS TD</button></td>
Then, you need to process the buttons for the row. ( Same button for each TD in the row. ) Something loosely like this:
if (isset($_POST["click_row"])) {
$clicked_row = $_POST["click_row"];
// Handle what you want done with this row...
}
Works well for me!
Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)
I have many tags. I want click each tag, then post/get the tag's value to another page.
In another page, received the values and make a mysql query. Then return the resalt data to the first page(do not make an iframe).
I think jquery post and load may be can do that (but have no idea how to combine two functiton). Or maybe there have any other way. Thanks.
here is my code
products.php
model:hml03
model:hml04
model:hml05<!--post value from products.php-->
data.php
<div id="data">
<?php
$result = mysql_query("SELECT id,name,details,add_date,model FROM ctw_products WHERE (MATCH (name,details,model) AGAINST ('+$_GET['get']' IN BOOLEAN MODE) Order By add_date DESC LIMIT 20 "); // get value with a mysql query
while ($row = mysql_fetch_array($result))
{
echo '<div class="name">'.$row['name'].'</div>';
echo '<div class="model">'.$row['model'].'</div>';
echo '<div class="details">'.$row['details'].'</div>';// how to return this part of datas back to products.php
}
?>
</div>
...<!--many other tags -->
<div class="show_data"></div><!-- get the data back show in here without refresh the page.
First you need AJAX to be able to do this. The simplest way to achieve this is use a library like jQuery
You can either download the library and include it locally or link to it directly from the jQuery site. the following code should allow you fetch data from data.php without a page refresh
<!--include the jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js"></script>
<script type="text/javascript">
function get_data(get){
$.get('data.php?get='+get, function(data) {
$('.show_data').html(data);
});
}
</script>
Next, modify your links to call get_data onclick like this:
model:hml03
Notice how we pass the id of the product to get_data, you need to do this for every link.
I would recommend you read up on Ajax and JQuery to really get the idea.
echo "<td> + manuf + </td>";
Is this above ever going to work??
I'm pulling results from a mysql db to edit the contents but need the jQuery functionality to edit it, hence the embedded javascript variable...
EDIT:
Sorry for the lack of context, its related to another question i've asked on here Mysql edit users orders they have placed
this is the end goal. To edit the order i place, i need to pull the results into an environment similar to how the user placed the order. So my thinking was to include the jQuery functionality to add items to a cart etc, then they could press submit and in the same way i used .Ajax to post the data to an insert php script i would post the values to an update php script! Is this backwards thinking, any advice welcomed!
I suggest you take a look at the follwing.
json_encode
Ajax
JSONP
Now your simplest solution under you circumstances is to do go for the json_encode method. Let me show you an example:
$json_data = array(
'manuf' => $some_munaf_data
);
echo "<script type=\"text/javascript\">";
echo "var Data = " . json_encode(json_data);
echo "</script>";
This will produce an object called Data, and would look like so:
<script type="text/javascript">
var Data = {
munaf : "You value of $some_munaf_data"
}
</script>
Then when you need the data just use Data.munaf and it will hold the value from the PHP Side.
Try just emitting the MySQL content with PHP:
echo "<td id='manuf'>".$manuf."</td>"
Then get the contents with jQuery like this:
var manuf = $('#manuf').text();
Would you not echo out the jQuery within a Javascript code island? You need the client-based code (jQuery) to be able to execute after the server-side code (PHP).
echo '<td><script language = "JavaScript" type = "text/JavaScript">document.write("");</script></td>';
Is this above ever going to work??
Nope. You'd need to output valid JavaScript for the browser to interpret:
echo "<script>document.write('<td>'+manuf+'</td>')</script>";
But that is a dreadful construct, and I can't really see why you would need this, seeing as the td's contents are likely to be static at first.
Consume you have the table echoed with php:
<table id="sometab">
<tr>
<td>
</td>
<tr>
</table>
The jquery for printing resuls in any td is :nth-child(2) takes 2 table td object :
<script type="text/javascript">
$(function(){
$("#sometab tr td:nth-child(2)").html("bla");
})
</script>
Is "manuf" a JS variable or part of a PHP output e.g. part of generated ?
Basically this can easily be done by:
mysql thru PHP(*I can't put table tag..sorry.):
while($row = mysql_fetch_object($result)) {
echo 'tr';
echo 'td a href="#" class="myres"'.$row->manuf.'/a /td';
echo '/tr';
}
then on your JS just attach a "click" handler
$(function() {
$(".myres").click(function() {
//my update handler...
});
});
i think you cant embed the jquery variable in the php like this .
you just give the class name here from here when edit will be click you will get the variable as in submit click in other questions .
I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.