I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.
Related
I'm building a two-way chat application that stores messages into a MySQL database. I would like to use Server Sent Events and have the PHP and HTML all in one page but the problem I'm facing is that the header cannot be set to text/event-stream or I will break the HTML.
My question is how can I have the PHP, JS and HTML on the same page when using Server Sent Events?
Here is my opening JS. I set the EventSource to index.php even though this might be wrong.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index.php");
source.onmessage = function(event) {
document.getElementsByClassName("message").innerHTML = event.data;
};
}else {
document.getElementsByClassName("message").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream");
}
else {
header("Content-Type: text/html");
}
//Database Stuff
$connect = mysqli_connect('localhost', 'user', 'Pass');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
?>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<?php echo "data: ".$row['mymessages']; flush();?>
</div>
</div>
<?php
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
?>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<?php echo "data: ".$row['yourmessages']; flush();?>
</div>
</div>
<?php
}
}
?>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
EDIT: I have tried separating the PHP the HTML and put the PHP logical part outside the HTML. I'm able to get Server Sent Events via inspector in Chrome but not sure how to loop through the DB entries in JS. I'm not comfortable with JS syntax.
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
if(isset($_POST['submit'])){
$send = $_POST['mymessage'];
$sendmsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('".$send."', '')";
}
if (!empty($_GET['yourmessage'])){
$recieve = $_GET['yourmessage'];
$recievemsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('', '".$recieve."')";
}
$connect = mysqli_connect('localhost', 'root', 'Walcott34');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$sqlrecieve = mysqli_query($connect, $recievemsg);
$sqlsend = mysqli_query($connect, $sendmsg);
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
echo "data: ".$row['mymessages']."\n\n";
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
echo "data: ".$row['yourmessages']."\n\n";
}
ob_flush();
flush();
}
}
else {
?>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index2.php");
source.onmessage = function(e){
document.getElementById("mymessages").innerHTML = event.data;
document.getElementById("yourmessages").innerHTML = event.data;
};
}else {
document.getElementsById('message').innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<div id='mymessage'>
</div>
</div>
</div>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<div id='yourmessage'>
</div>
</div>
</div>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
<?php } ?>
If your after it being in one file you just need the one outer if statement which separates the two logical parts.
<?php
if ($_SERVER["HTTP_ACCEPT"] === 'text/event-stream') {
// event stream code
...
while (true) {
...
} else {
// client side code
?>
<head>
<meta name="viewport" content="w
...
<?php }
You cant intertwine the two parts like your doing:
<div class='message'>
<?php echo "data: $row['mymessages']"; flush();?>
</div>
Your serverside part is incomplete but that's beyond the scope of the question,ive commented with a link to a working example.
I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
I am doing a project to remotely display the data on the P10 Modules. I made the website for it, but whenever I want to retrieve data from the specific webpage on my website I get the error that is mentioned below;
The error I get when I try to retrieve data from the webpage1
The URL for the webpage is http://haider.paks.pk/test1/newfile.txt
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("b2a5a77ff21b1f1b4e9b8d9099c2f834");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://haider.paks.pk/test1/newfile.txt?i=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>
</html>
How can I possibly solve this issue? How to enable javascript in the coding? Where I would do it?
The codes for the web pages are;
Index page (Main Page)
<?php
//include auth.php file on all secure pages
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Home</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<form action="get_msg.php" method="post">
<p>Select Department </p>
<br>
<select name="dept">
<option value="cs">CS</option>
<option value="ee">EE</option>
<option value="btn">BTN</option>
</select>
<p>Enter your message:<br />
<textarea name="sms" rows="10" cols="40"></textarea></p>
<p><input type="submit" value="Send it!" onclick="show()"></p>
</form>
<script>
function show() {
alert("Message send successfully");
}
</script>
<input type="button" name="b1" value="Show History"onclick="location.href='history.php'">
<p>This is secure area.</p>
<p>Dashboard</p>
Logout
</div>
</body>
</html>
get message page (The page that retrieves the sent message from the server
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
**Index2 webpage (The webpage that retrieves the message from get message webpage and sends it to the text file **
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
I have resolved the issue. There is nothing wrong with the code. The only thing due to which this issue raised was that I was using free domain for my website. When I uploaded the same files on a paid hosting service, the issue was resolved and my arduino was able to retrieve the data from the web server.
So I am trying to do something simple. There is a form, it does a self post and I want to get that post information from JQuery and put it into a div.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
JQuery here to catch button click and do a "PHP_self":
<script>
$(document).ready(function(){
$(".gettingpostbutton").click(function(){
$.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", function( data ) {
$("#add_post_information_html_here").append(data+" number from $_POST");
});/**/
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = test_input($_POST["number"]);
}
For SQL Injection:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Basic Form:
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
put a number: <input type="text" number="number">
<br><br>
<input type="button" name="action" class="btn btn-success gettingpostbutton" value="Add Number" />
</form>
Put info to page either through PHP but prefer to do it through JQuery:
<?php
echo "<h2>Your Input:</h2>";
echo $number;
?>
<div id="add_post_information_html_here"></div>
</body>
</html>
Result:
Hey Im having an issue in accessing the variable from JQuery Ajax. I ve tried everything. I even added cdn script tag to both files. but I keep getting this error of undefined index
Notice: Undefined index: head in C:\xampp\htdocs\Project\View.php on line 20
Anyone has any idea wats wrong with the syntax. I have attached both my files below.
SearchProjects.php
<html>
<head>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#assign tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
$('td').on('click',function() {
var heading=$(this).text();
alert(heading);
$.ajax({
url: "View.php",
type: "POST",
data: {head: heading},
success: function(data){
alert("success");
}
});
});
</script>
</head>
<body>
<div>
<div class="col-md-12"><br/></div>
<?php
session_start();
$No="Not Assigned";
require("DB.php");
$query="SELECT `ID`, `Assigned_By`, `name`, `path`, `heading`,`Assigned_to`, `Completed`, `Date`, `Due_Date`, `Price` FROM `assign` where `Assigned_to`='Not Assigned' order by Date Desc";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
echo "<table class=table table-hover id=assign>"
."<thead>"
. "<tr> "
. "<th>ID</th>"
. "<th>Assigned_By</th>"
. "<th>Name</th>"
. "<th>Path</th>"
. "<th>Heading</th>"
. "<th>Assigned_To</th>"
. "<th>Completed</th>"
. "<th>Due_Date</th>"
. "<th>Submission_Date</th>"
. "<th>Price</th>"
. "</tr> </thead> ";
while($row = $result->fetch_assoc()) {
echo "<tr>"
. "<td>".$row["ID"]."</td>"
. "<td>".$row["Assigned_By"]."</td>"
. "<td>".$row['name']."</td>"
. "<td>".$row['path']."</td>"
. "<td>".$row['heading']."</td>"
. "<td>".$row['Assigned_to']."</td>"
. "<td>".$row['Completed']."</td>"
. "<td>".$row['Date']."</td>"
. "<td>".$row['Due_Date']."</td>"
. "<td>".$row['Price']."</td>"
. "<td><a class=btn btn-default href=View.php role=button>Show More!</a></td>"
. "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
?>
</div>
</body>
View.php
<html>
<head>
<title>TODO supply a title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<?php
session_start();
if(isset($_POST['head'])){
echo $_POST['head'];
}
$filename="CV.docx";
// $filename=$_SESSION['filename'];
//echo $filename."<br/>";
require("DB.php");
$query="SELECT `heading` FROM `assign` where `name`='$filename'";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$heading=$row['heading'];
$_SESSION['heading']=$heading;
}
}
else {
echo "0 results";
}
$dir = "Assigns/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if(!($file=="." || $file=="..")){
$f=explode(".",$file);
if(strcmp($f[0],$heading)){
if(!file_exists("Assigns/$file")) {
die("File not found");
}
else{
$my_file = "Assigns/$file";
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
}
}
}
}
closedir($dh);
}
}
if($_SERVER['REQUEST_METHOD']== 'POST'){
if (isset($_POST['save'])) {
$assigned_to=$_SESSION['username'];
echo $assigned_to;
echo $filename;
$query="UPDATE `assign` SET `Assigned_to`='$assigned_to' WHERE `name`='$filename'";
$result=mysqli_query($PDB,$query);
if($result){
echo "wohooo";
}
else{
echo "nooo";
}
}
else if (isset($_POST['submit'])) {
// echo "submit";
header('location: Solution.php');
}
}
?>
<div class="container">
<form action="View.php" method="post">
<h1 style="clear:both;"><?php echo $heading."<br/>" ?> </h1>
<div class="form-group">
<?php echo $data; ?>
</div>
<div class="col-md-12 col-md-offset-6">
<input type="submit" name="submit" value="Submit Solution">
<input type="submit" name="save" value="Save Changes">
</div>
</form>
</div>
</body>
Always check the existence of a variable/array index before using it:
$head = isset($_POST['head']) ? $_POST['head'] : null;
//may check nullity of $head
There seem to be two things going on: First of all, the click handler for the td is not attached because the DOM was not ready, wrap your jQuery code in
$(function() {
//your code
})
Also, the click event on the tr and on the td are both fired...