echo "<tr onclick='window.location=("www.google.com")'>
<td>something</td>
<td>something</td>
</tr>"
i have written code like this but it is not working.i dont know where to put single quotes and double qoutes.
I dont know how to write onclick for in php
please suggest me
Avoid using echo for HTML. Leave PHP mode and go into output mode.
Avoid using nested literal values. Write each language as a separate variable, use suitable escaping functions to add whatever quotes you need and then put them together.
By keeping everything as separate layers and dealing with them one at a time, and by using functions instead of trying to write your escapes manually, you make things much easier to maintain.
$url = "http://www.google.com";
$js_string_literal_url = json_encode($url);
$js = "window.location = $js_string_literal_url";
$html_safe_js = htmlspecialchars($js);
?>
<tr onclick="<?php echo $html_safe_js; ?>">
<td>something</td>
<td>something</td>
</tr>
That said, you should also avoid:
Features which depend entirely on JS
onclick attributes
Write HTML that works, and then enhance with JS.
If you want to link somewhere: use a link:
<tr>
<td>something</td>
<td>something</td>
</tr>
If you want to make that link work (using JS) for the whole table row, bind an event listener that looks for clicks, and then find the first link in the row that was clicked on.
document.querySelector("table").addEventListener(follow_link_in_row);
function follow_link_in_row(event) {
var table_row = event.target;
while (table_row && table_row.tagName.toLowerCase() !== "tr") {
table_row = table_row.parentNode;
}
if (!table_row) { return; }
var link = table_row.querySelector("a[href]");
var url = link.href;
window.location = url;
}
Related
I am trying to make the entire row of a table clickable. I have looked at a bunch of tutorials and they all seem pretty simple but I can't seem to get it to work. I tried DoNav and that didn't work, the simple onclick attribute doesn't work, what am I doing wrong? I am using mysql, php, and html. Thank you for your help!
echo '<table>';
echo '<tr>';
echo '<th>Name</th><th>Checked In?</th><th>ID</th>';
echo '</tr>';
while($row = $CheckedIn->fetch_assoc()){
echo '<tr onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this,false);" onclick="document.location="www.engineering.us/gena/details.php";">';
echo '<td align="left">';
echo $row['ChildName'];
echo '</td>';
echo '<td align="center">';
;
echo $row['checkedin'];
echo '</td>';
echo '<td align="center">';
echo $row['P_Id'];
echo '</td>';
echo '</tr>';
}
echo '</table>';
onclick="document.location="www.engineering.us/gena/details.php";"
this should be
onclick="document.location='www.engineering.us/gena/details.php';"
Also another tip, you have more HTML than php, so it is better to use multiple php tags rather than echo called many times. That way it would be little easier to find such mistakes.
Edit
You should also escape the apostrophe in case you are still going with php
Picking up from what georoot said, use PHP within your HTML. It makes the markup a lot more readable and usually allows your program to add syntax highlighting, making it easier to read. I've added two additional classes ("js-table" and "table-tr") which I'll explain in a bit. Another important point is that the URL is in a new attribute on the table row: data-url.
<table class="js-table">
<thead>
<tr>
<th>Name</th>
<th>Checked In?</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<?php while ($row = $CheckedIn->fetch_assoc()): ?>
<tr class="table-tr" data-url="http://www.engineering.us/gena/details.php">
<td><?php echo $row['ChildName']; ?></td>
<td><?php echo $row['checkedin']; ?></td>
<td><?php echo $row['P_Id']; ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
The "table-tr" class allows us to target the table rows in CSS. There is no need to use JavaScript for something so simple. Even changing the colour of the text within the table cell is very easy in CSS. This technique has the other advantage that it can be easily changed without having to modify any HTML, PHP or JavaScript - it's a purely stylistic thing.
.table-tr:hover {
background-color: red;
}
Finally, since you're using jQuery, we can take advantage of that new "js-table" class. The "js-" prefix states that the class is used for binding functionality and it should not be styled. This script simply bind a click event to the table that listens out for a user clicking on a table row with the data-url attribute. When that happens, the page is re-directed (using window.location instead of document.location - it may work either way, but I've always used window.location) to that URL. This allows you to change the URL later on or change it per row without having to change any of your JavaScript.
$(function () {
$(".js-table").on("click", "tr[data-url]", function () {
window.location = $(this).data("url");
});
});
I hope that helps.
Consider using the following code:
$("#Table tr").click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
var value = $(this).find('td:first').html();
window.location.href = "url";
});
Where Table is the your table name and url is the address you want to navigate to
I think you should try to do that with JQuery.
HTML
<tr class="table-tr"></tr>
JQuery
$('.table-tr').on('click', function(){
window.location = "your url here";
});
Please Change your code with this
<tr onclick="window.location.href=www.engineering.us/gena/details.php">
I am using PHP and MySQL to loop through products and generating HTML code that consists of an img tag with an onClick event that calls a Javascript function. I want to pass PHP variables via the onClick event to a Javascript function. I'm using jQuery and thought it would be a good idea to use PHP's json_encode() function and jQuery's jquery-json plugin.
My PHP code looks like this:
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a href=\"javascript:;\" onClick=\"changepic('" . htmlentities($onclick) . "')\">";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
As you can see my Javascript function is called changepic(). I've left out a bit of code that is irrelevant to this question (i.e. the database access code and deciding where the thumbnail image is).
My Javascript code is:
function changepic(productarray) {
var productid = $.evalJSON(productarray).productid;
var productdesc = $.evalJSON(productarray).description;
alert(productid);
}
I'm not really doing anything yet with the PHP variables that I'm passing to the Javascript array, I'm just trying to get it to work first! My ultimate aim is to use jQuery to insert the product description into a <div>
A sample product detail might look like this:
ProductID: 30c7508008ac7597619ad9b90a97b40f
Description: <p>Wide and Narrow Bands<br>
Set with Top-Quality Diamonds</p><p>
As you can see the description contains HTML code, as well as a newline after the <br> tag.
The HTML that is generated looks like this:
<img src="products/tn-30c7508008ac7597619ad9b90a97b40f.jpg" width="100" height="100">
When I run this I get a Javascript error:
Event thread: click
Uncaught exception: SyntaxError: JSON.parse: Unescaped control char in string: "<p>Wid
Error thrown at line 18, column 2 in changepic(productarray) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
var productid = $.evalJSON(productarray).productid;
called from line 1, column 0 in <anonymous function>(event) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
changepic('{"productid":"30c7508008ac7597619ad9b90a97b40f","description":"<p>Wide and Narrow Bands<br>\r\nSet with Top-Quality Diamonds<\/p>"}')
From what I can see I've done something wrong with encoding the JSON string. I've done some Googling and found some people that say no encoding is necessary (I tried that and the product description was taken as HTML and showed up in the page), others say to use addslashes() and some say htmlentities().
Do I need to do something in the Javascript function to decode it before I try to use it with evalJSON()?
I usually just do this,
var foo = <?php echo json_encode($foo); ?>;
and I don't really see how this can result in any sort of an "injection" attack as long as json_encode is doing its job.
I don't understand why you are getting into so much mess.. here is the solution and it works
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a id='test' href='' var='$onclick'>";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
Here is your jquery:
$(function(){
$("#test").click(function(){
var img = jQuery.parseJSON(($(this).attr("var")));
alert(img.description);
});
});
Now since you have the json object you can create div tag and put the variables inside or put the content on already existing div tag. I am sure you know what to do here.
Dins
I think I was over-complicating things, I didn't really need to use JSON at all.
I got this working by changing my PHP code to this:
$productid = $productsRow['ProductID']
$description = rawurlencode($productsRow['Description']);
echo "<a href=\"javascript:;\" onClick=\"changepic('$productid','$description')\">";
Then my Javascript looks like this:
function changepic(productid, description) {
description = decodeURIComponent(description);
alert(description);
}
This works fine so now I can continue and actually do something useful in the Javascript function.
I have been using this code for deleting data from database. What i wan is whenever a user clicks an image link to delete data from the confirm function prompts up and ask for action, i am getting error in this code.
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
echo "<a href=".$delurl.";
echo "onclick='return confirm('Are you sure you want to delete.')'>".$img."</a>";
Maybe the error is in double quotes or single quotes, Any help
Thanks in advance
change
echo "<a href=".$delurl.";
to
echo "<a href=\"".$delurl."\" ";
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
$confirm_box <<<CONFIRM
<a href="$delurl"
onclick="return confirm('Are you sure you want to delete?')">$img</a>
CONFIRM;
// then elsewhere ...
echo $confirm_box
Always tend towards using the HEREDOC syntax to construct HTML/JS output, it will save you a lot of heartache. Just watch out for the major gotcha, DO NOT INDENT THE FIRST/LAST lines of the heredoc declaration.
EDIT The benefit being that you can mix single and double quotes as much as you like, you only have to worry about the JS quoting - PHP variables are interpolated without the quotes. You can further wrap curly quotes around your PHP variables like {$this} to make it easier to read, but also to delineate $this and {$this}tle.
I would us the following instead of escaping, this is more readable to me:
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
?>
<?=$img?>
You can, may and should escape when handling stuff like this:
echo "<a href=\".$delurl.\"";
echo " onclick=\"return confirm('Are you sure you want to delete.')\">".$img."</a>";
lg,
flo
Is there a way I can use Jquery to insert '' tags after every three dynamically generated table cells so that I end up with a dynamic three column table?
Please excuse my lack of knowledge, I'm literally trying to write my first jquery script ever, so I know absolutely nothing. I know php and I have a table that has a loop within it that is dynamically creating <td></td> with the information inside each tag. In other words it is dynamically creating the table cells within a static <tr></tr> tag. The problem is that it keeps outputing tables without breaking them up into rows which leaves me with a bunch of columns. I've read other articles on this but none seem to have the exact same problem as I do, and I am still struggling to understand how to write custom Jquery code.
The php code is very long and is full of numerous if statements and other functions so I'm not going to post it here but just to make it a little simpler, I made miniature mockup of what I'm trying to do.
<table id="mytable" width="266" border="1" cellspacing="10" cellpadding="10">
<tr>
<?php
$x=0;
while (have_products($x)) {
echo '<td>' . somelongassfunction() . '</td>';
$x++;
if (fmod($x,3) == 0) {
echo '</tr><tr>';
continue;
}
if ($x==20){
echo '</tr>';
}
}
function somelongassfunction(){
return 'Hello';
}
function have_products($a){
return $a<=20;
}
?>
</table>
This code loops and dynamically adds table cells up to the limit I give it which would represent my database items. Every three rows, it adds either a <tr></tr> or just a </tr> depending on whether the loop continues or not. This creates a 3 column table. I can't apply this code for my script because it is a very long and complex script that has a lot of if statements and functions. There is no way of doing it like this without breaking the code or having to rewrite everything from scratch all over again.
Is there anyway I can append the tr tags dynamically with Jquery and how would I go about to applying this to?
The jQuery approach would be to loop through all of the tabs, and add them to newly created tags, which themselves are added to the html of the table. Roughly:
var thisCount=0;
var currenttag="<tr />";
var table=$("table");
$("td").each(function ()
{
if(thiscount==2)
{
table.appendChild(currenttag);
thisCount=0;
currenttag="<tr />";
}
currenttag.appendChild(this);
}
( this is just to give an idea, not intended as a formal JQ answer. If anyone wants to edit it so it works fully, feel free ).
You can use a selector to select every third row:
$('#table_id > tr:nth-child(3n)').whatever_function()
However if you are trying to append end /tr tags, try doing it in PHP using a counter that resets itself (this code should get you started):
echo "<tr>";
$x = 0;
$y = 0;
while (have_products($x)) {
echo '<td>' . somelongassfunction() . '</td>';
$y++;
if ($y == 3) {
$y = 0;
echo "</tr><tr>";
}
$x++;
}
echo "</tr>";
I've been asking similar questions here today, but I'm seeing I think the issue is with how I am calling my data?
I'm trying to replace a nav bar with ajax that will load contents into a div.
The nav bar is this:
<ul>
<li>Monthly</li>
<li>Daily</li>
<li>Admin</li>
<li>Help</li>
</ul>
Then I have this to replace the div:
<div id="targetDiv"></div>
the getData function is an innerHTML request:
<script language = "javascript">
function getData(dataSource, divID)
{
$.ajax({
url: dataSource,
dataType: 'html',
success: function(data) {
$('#' + divID).html(data);
}
});
}
</script>
When I click the nav links, the HTML loads into the div, but the contents of my include files also contain PHP functions and jQuery that needs to execute when being loaded and they are just ignored. I've seen this question asked a lot here, but these seem to only relate to jQuery?
To be clear, when I click the nav links, I get a 200 OK in firebug console, but only HTML is coming back and populating div.
Here is my most recently cleaned include file with changes from Jonathan's suggestions. At this point, I am getting output up the the </tr> after the help button (line 15) but no output past that...
<?php
session_start();
?>
<table width='100%' border='0'>
<tr class='twentyfivepxheight'><td></td></tr>
<tr>
<td width='40%' valign='top'>
<div class='left_agenda_items'>
<table width='80%' align='center' border='0'>
<tr class='twentyfivepxheight'>
<td align='left' class='title5 bottompadding unselectable'>Daily Agenda<a href="javascript:void(0)" class="supernote-click-note1">
<img src="/images/help-sm.jpg" alt="Help Button" /></a>
</td>
</tr>
<?php
$numric_time = getNumericTime($_SESSION['userData']['timezone']);
$query = "SELECT * FROM events WHERE date(convert_tz(StartDate,'+00:00','". $numric_time."'))='$currentDate' AND UserID='" . $_SESSION['userData']['UserID'] ."' ORDER BY StartTime";
$result = mysql_query($query);
if(mysql_num_rows($result))
{
while($row = mysql_fetch_assoc($result))
{
$eventID = $row['EventID'];
$eventName = $row['EventName'];
$startDate = $row['StartDate'];
$description = $row['Description'];
$assignedTo = $row['AssignedTo'];
$PTLType = $row['PTLType'];
$parentEventID = $row['ParentEventID'];
$textclass = "greentext unselectable";
$text = "Main event";
//$url = SITE_URL ."/agenda-view-event.php?eventID=$eventID&date=$currentDate&day=$i&type=A&date=$currentDate";
$url = SITE_URL ."/agenda-view-event.php";
if($PTLType == 2) // To do's
{
//$divRed[] = $eventID;
$url = SITE_URL ."/agenda-view-timeline.php";
$textclass = "redtextDaily unselectable";
$text = "To do";
$html_todos .= '
<tr id="redtext' . $eventID . '">
<td id="rowbox'.$eventID.'" class="'. $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'parentEventID='.$parentEventID.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">
' . $eventName . ' - (' . $text . ')
</td>
</tr>';
}
elseif($PTLType == 3) //Completed
{
//$divBlue[] = $eventID;
$url = SITE_URL ."/agenda-view-timeline.php";
$textclass = "blueTextDaily unselectable";
$text = "Completed";
$html_completed .= '<tr id="bluetext' . $eventID . '"><td style="display:none;" id="rowbox'.$eventID.'" class="' . $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'parentEventID='.$parentEventID.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">' . $eventName . ' - (' . $text . ')</td></tr>';
} else { //main events
//$divMainEvent[] = $eventID;
$html_main_events .= '<tr id="mainEvent' . $eventID . '"><td id="rowbox'.$eventID.'" class="' . $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'date='.$currentDate.'\', \'day='.$i.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">' . $eventName . ' - (' . $text . ')</td></tr>';
}
}
echo $html_main_events . $html_todos . $html_completed;
} else {
?>
<tr>
<td>
<span class="a_dateformat">You have no agenda items due today!</span>
</td>
</tr>
<?php
}
?>
</table>
</div>
<input type="hidden" id='lastselected' value='' style="" />
</td>
<td class='verticalborder'> </td>
<td width='59%' valign="top" align="center">
<div id="agendaLoader" style="display:none;">
<img src="images/ajax-loader-orange.gif" alt="wait" />
</div>
<div id="agendaViewDiv" style="display:none;"></div>
</td>
</tr>
<tr>
<td colspan="3">
</td>
</tr>
</table>
But see how I commented out the jQuery to make it work?
If that is not commented out, I don't get any output. The problem is that I need that jQuery to properly build the page.
For anybody who stumbles across this "answer," please note that it was not intended to be so broken-up. Each portion of this answer was added at a later date following exchanges with the OP in the comments. The items on top are the latest additions whereas the furthest items down were earlier additions.
Jonathan Sampson
Call to undefined function
Because this page is typically included, and not called directly, there may be some things that won't be available when requested. You indicated in the comments that the function getNumericTime() doesn't exist, and is causing an error.
You'll want to make it exist, but you don't want to just redeclare it, or else that will cause problems for you when you request this page as an include-file to another page that already has that function. So what you'll want to do is check whether the function exists, and create it if it doesn't.
if (!function_exists("getNumericTime")) {
function getNumericTime($foo) {
// get the function logic and place it here
}
}
Now, when you call the include-file directly, the function will be created if it doesn't exist. When you call the old-fashioned way, with this file being included, the if-statement will simply skip pass the new function declaration, since the function already exists.
If this function exists within a functions file, you can include it, but be sure to use include_once() instead of include(). include_once() will not include the file if it's already be included once before. Given the fact that this page is occasionally in another environment where the functions include has already taken place, we want to be sure not to include it again, so we use the include_once() method.
Missing connection and selection...
You're attempting to perform queries, yet there's no database connection on this page. There is also no mysql_select_db() call to select from a specific database. Without these, your queries won't succeed and your data won't be returned.
// Our connection to mysql
$conn = mysql_connect($host, $user, $pass) or die(mysql_error());
// Which database we're using
mysql_select_db($dbname) or die(mysql_error());
Once that connection is made (within index.php, for example) we could do an include:
include("foo.php");
The contents of foo.php now have a connection opened so they can perform queries, call stored-procedures, etc. This is only the case because it's being included into a page that has an open-connection.
If we were to access foo.php directly, which is what you're doing with your ajax-request, we wouldn't get the results we want, because foo.php doesn't provide its own database connection - it depends on index.php (which it is often times included into) to provide that connection.
From PHP to HTML to PHP...
One thing that often times causes problems outputting HTML progressively through a PHP Script. Often times you'll see numerous echo statements followed by HTML strings that are littered with back-slashes to escape certain output. Not only is this tedious to write, but it's a pain to search when problems arise. HTML rarely needs to be within PHP. When you need to output HTML, get out of your PHP tags for a moment:
<?php
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_assoc($result) { ?>
<tr>
<td>Data Here</td>
<td><?php print $row["foo"]; ?></td>
</tr>
<?php }
} else { ?>
<tr>
<td>No records found</td>
</tr>
<?php }
?>
Notice how it's easier to tell when my HTML is wrong someplace, and it's easy to jump from writing markup to writing PHP. Ideally, you wouldn't even do it this way, but this is an improvement over what you currently have.
Properly using $_SESSION
After giving a look at your code, I noticed that you're calling values out of $_SESSION, or trying to at least. You can only do this if you have called session_start() at the top of the page. Your code lacks this, which may be the reason you're not getting anything back as an integral part of your SQL Queries is missing. Add the following to the very top of your script:
<?php session_start(); ?>
PHP Code Not Executing?
If your PHP isn't executing, there's a problem with the script or the server, but not with jQuery. Check to make sure you have both the opening and closing PHP tags in the script you're requesting:
<?php
/* and */
?>
Simplifying things
You could simplify and clean up your code a bit too. First of all, let's create a new nav-bar:
<ul id="nav">
<li>Index</li>
<li>About</li>
<li>Contact</li>
</ul>
Note how I'm linking directly to the files, and not using any javascript to cancel out my clicks. This way, when a user stumbles onto my site without javascript enabled, they're not faced with a broken website, they can still get around.
Without interspersing javascript in our HTML, we'll bind up some logic to these nav-links:
$(function(){
// Attach logic to all links
$("#nav a").click(function(e){
// Prevent link from redirecting page
e.preventDefault();
// Load next page into #targetDiv
$("#targetDiv").html("").load($(this).attr("href"));
});
});
And that's it. You're done.
This answer is in response to the follow part of the question:
When I click the nav links, the HTML
loads into the div, but the contents
of my include files also contain PHP
functions and jQuery that needs to
execute when being loaded and they are
just ignored.
Note that the JavaScript that gets returned from XMLHttpRequestObject.responseText will not execute when inserted into the DOM text with innerHTML as you are doing.
You may want to check the following Stack Overflow post for a couple of solutions around this issue:
Can scripts be inserted with innerHTML?
However, if you are using jQuery, you can replace all the code in getData() with the following:
function getData(dataSource, divID)
{
$.ajax({
url: dataSource,
dataType: 'html',
success: function(data) {
$('#' + divID).html(data);
}
});
}
When the jQuery ajax() method is called with the dataType: 'html' option, included script tags are automatically evaluated when inserted in the DOM. You may want to check the following Stack Overflow post for further reading on this:
When loading an html page via ajax, will script tags be loaded?