Passing Parameters To PHP Table Hyperlink - javascript

I want the second and third columns of my php table to be a hyperlink to a different page for each row. I need to pass 3 parameters to the hyperlink
1) The value from the first column - empID listed in the table below
2) The value from $weekStart - selected from a input type="date" at top of page
3) The value from $weekEnd - selected from a input type="date" at top of page
I am trying this syntax, but it is not passing in the parameters and I am getting a page not found error. How should this syntax be altered so that it passes all 3 params and navigates to the appropriate page?
Week Start:<input type="date" name="weekStart">
Week End:<input type="date" name="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
?>
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td>'.$Row['DailySales'].''" . $res->DailySales . "</td>";
print "<td>'.$Row['SalesForWeek'].''" . $res->SalesForWeek . "</td>";
print "</tr>";
}

You didn't append the string well. Please try the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['SalesForWeek']."</a>" . $res->SalesForWeek . "</td>";
print "</tr>";
}
If it still shows not found page, then please check the file names.
Update: I hope you need to replace some variables in your loop as updated in the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->SalesForWeek."</a></td>";
print "</tr>";
}

Completely untested and I'm not 100% sure what the data in those links were supposed to be doing, but I think this should give you a solid starting point and you can tweak the HTML generation to get what you want.
I wouldn't bother trying to do it in PHP at all, pass the entire data set to JS and do it there.
Week Start:<input type="date" name="weekStart" id="weekStart">
Week End:<input type="date" name="weekEnd" id="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
// Create a JSON version of your data to pass to the script
$data = json_encode( $tsql );
?>
<!-- Create an empty table for your data-->
<table id="employee-table"></table>
<script>
$("#submitForm").on("click", function(e) {
// Stop the form from reloading the page
e.preventDefault();
// Set up your variables, you'll need to add ID's to the form inputs
var employees = <?php echo $data; ?>;
// See the employees data in your inspector console
console.log(employees);
var weekStart = $("#weekStart").val();
var weekEnd = $("#weekEnd").val();
// Generate the HTML for all the employees
var html = "";
for( var1=0; i<employees.length; i++ ) {
html += "<tr>";
html += "<td>" . employees[i].EmpID . "</td>";
html += "<td>" + employees[i].DailySales + "</td>";
html += "<td><a href='WeeklySales.php?param1='" + weekStart + "'&param2='" + weekEnd + "'&param3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>

Related

How can i display data from selected row in textarea

I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>
For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.
Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered

On table row click, alert box shows click value

i'm having problems where when i click the tablerow, nothing is being shown.
When I click lets say the row where customername= 'John', the name 'John' should appear on a alert box, but nothing happens.
This is my table click code.
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
And, here is my generating of table code.
if(!empty($_GET['q'])){
$q = $_GET['q'];
$query="select * from customer where customername like '$q%'";
$result = mysqli_query($dbconn,$query);
echo "<div id='parentElementIdHere'>";
echo "<table id='test' border=3>
<tr>
<th>Customername</th>
<th>nric</th>
<th>email</th>
<th>mobileno</th>
<th>telephoneno</th>
<th>address</th>
<th>postalcode</th>
<th>datejoined</th>
<th>points</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['customername'] . "</td>";
echo "<td>" . $row['nric'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['mobileno'] . "</td>";
echo "<td>" . $row['telephoneno'] . "</td>";
echo "<td>" . $row['occupation'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['postalcode'] . "</td>";
echo "<td>" . $row['datejoined'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
Could the problem be because my table generated is constantly changing because of ajax?
To get name value for click on any value of the row
$("tr").click(function() {
var str = this.innerText;
var i = str.split('').indexOf(" ");
alert(str.slice(0, i));
})
http://codepen.io/nagasai/pen/QENwgQ
to get table cell value on click
$("td").click(function(){
alert(this.innerText);
})
codepen URL for reference- http://codepen.io/nagasai/pen/jrqEBz
Hope this is helpful for you
There are two main problems with your code:
Your selector '#test tr #name' says to select all elements with id="name" that are descendants of tr elements, but it is actually your tr elements that all have that id. (And speaking of them all having that same id, duplicate ids is invalid HTML.)
Calling .click() binds a click handler to elements that exist at that moment. Which means that when your table changes due to an Ajax call your click handler would not work for the newly loaded/created elements even if you fixed the selector.
The solution to both problems is to use a delegated event handler, which you bind to the table element's parent (or to the nearest ancestor element that does not get overwritten by the Ajax call):
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
});
When a click occurs on any descendant element of the parent element, jQuery will check if the specific clicked element matches the selector that is the second argument to the .on() method, and if so it will call your function with this set to the matching element. Because the matching element is a tr element, you would then use .find("td").first() to get that row's name td.
Demo: https://jsfiddle.net/269Lt9hm/
I managed to solve it. I tested with a non ajax generated sql table and did it. Then i brought over the javascript code over to this file and tried it out. This is the code i used.
$(document).ready(function(){
}).on('click','.test tr',function(){
var id = $(this).attr('value');
alert(id);
});
Thanks to all who helped me i appreciate it!

Using jQuery to get the data of a JSON Object

I am new to jQuery and JSON. I have the following PHP code (getData.php) performs query from the database:
<?php
header('Content-Type: application/json');
....
// some code here
....
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
// convert to integer value if there is a bug after passing json_encode
$rev=intval($info['bIRevNum']);
$name=$info['bIName'];
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
$my_arr[]=array('br'=>$name,'rev'=>$rev);
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// json encode
echo json_encode($my_arr);
?>
After use echo 'json_encode' here I can see the JSON object under this format
[{"br":"itemsb1","rev":37},{"br":"itemb2","rev":45}] on my page.
Now I want to access the integer of rev element of the object (37 and 45) for future usage by jQuery in a different PHP file, lets call it index.php and with the below script
<html>
.....
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value){
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
});
</script>
...
// test here
<!---jquery--->
<div id="div1"><h2>CHANGE >>>> ....!!!!</h2></div>
<button>Calling from different PHP file</button>
</html>
If it is correct, when I click on the button "Calling from different PHP file" it should appears the value of JSON object as 37, 45.
I have tried many ways, but it does not display anything on my page.
Please help me with this!
It appears your problem is that you are echo'ing the html as well as the JSON. try removing the 'echo' from these lines
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
DO NOT delete this line:
$my_arr[]=array('br'=>$name,'rev'=>$rev);
Also make sure your javascript is syntax correct
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value) {
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
Ensure that the only content coming back from getData.php is JSON-formatted; otherwise, it won't be parsed correctly. If you visit getData.php in your browser directly, you should only see JSON content, and nothing else (including errors, warnings, etc.). Your jQuery looks good; so the issue would have to be whatever content is coming back from the PHP script. I just whipped up a trivial test case using this PHP:
<?php
header('Content-type: application/json');
$my_arr[]=array('br'=>'something','rev'=>'2.0.5');
echo json_encode($my_arr);
?>
Using the exact HTML you provided, that works just as expected.

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Display data in tabular manner in PHP form

I want to do something like this..
I have a update form in PHP, which contains around 15 fields,
I want to show some data in tabular manner while you open the page for update..
Senario:
If you want to update a record of a person on day to day basis, I have the feature with me to search out that person form database, and when you click on update data..
it should show in a manner that,
field1.....----------
field2.....----------
field3.....----------
and now,
for field4,5,6,7
if these fields contain the data then show in a table manner with fields 4,5,6,7 as coloums and no of rows depending upon the number of entries (should be non editable)(assume the case of multiple input)
then form will continue.
field4.....--------
field5.....--------
field6.....--------
field7.....--------
typically these field(4,5,6,7) gets their value update frequently and I have to maintain the previous inputs also.
help me out with some solution, as I am unable to figure out how to do this?
before that i was using this.. here i was having a form field which can generate 5 options, and will populate the fields with data if u have entered before, now i want to change the display as I don't want user to play with the old data, so I want to show old data into a table and enter new data via a simple text field,
as their is no point to keep these multiple input form field as user is updating only one value at a time.
<script>
function Submitted_Date(value,object)
{
value = document.getElementById("subdate_num").value;
if (value > -1) {
var input= new Array(value);
var p;
//alert("Enter The fields You Know ");
var ele = document.getElementById("subdate");
if(ele.hasChildNodes())
{
var len = ele.childNodes.length;
while(ele.childNodes.length - value > 1)
{
ele.removeChild(ele.lastChild);
}
}
for (var i=len-1;i<value;i++)
{
p= i+1;
input[i] = document.createElement('div');
input[i].innerHTML = 'Submitted_Date' + p + ': <input type="text" value="" name="subdate' + p + '" id="subdate' + p +'" size = 25 onclick="javascript: showCalendar("Submitted_Date'+ p +'")"/>';
document.getElementById("subdate").appendChild(input[i]);
var subdate = 'subdate' + p;
}
}
document.getElementById("subdate1").focus();
}
</script>
<tr>
<td> Submitted Date :
<select name="subdate_num" id="subdate_num" onChange="return Submitted_Date(this.value,this.form)">
<?php
for ($i=0;$i<=5;$i++)
{
if ($i==0) { $temp = "<option value=$i> - </option>"; echo $temp; }
else { $temp = "<option value=$i>$i</option>";
echo $temp; }
}
?>
</select></td>
</tr>
</table>
<table>
I think this is what you want, this will show the information in a table with as many (or few) columns as you want
$query = "SELECT * FROM announcements ORDER BY announceid";
$result = mysql_query($query);
echo "<table border='1'>
<tr>
<th>Announcement ID</th>
<th>Announcement Name</th>
<th>Announcement Category</th>
<th>Approved?</th>
<th></th>
</tr>";
if ($result && mysql_num_rows($result) > 0) {
$x = 0;
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['announceid'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['category_name'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo '<td>Edit</td>';
echo "</tr>";
$x ++;
};
echo "</table>";
Let me know if that is what you are looking for, or if there is any other way I can help. Thanks!

Categories

Resources