Get the row number onclick using Ajax - php

I have wore below code and its working.But I want row number when a ROW clicked(Hope Ajax is okay) and pass it to a php code in same page. I tried javascript it worked,bt not in the way I want. If its in Ajax its better. Any HELP would b gratefull :)
if(isset($_POST['search'])){
$search=mysqli_query($con,"SELECT * FROM bus_fares WHERE route_no='$_POST[route_no]'");
$num_rows = mysqli_num_rows($search);
$search1=mysqli_query($con,"SELECT fare FROM fare limit $num_rows ");
$x = 0;
echo" <table id='my_table'><tr><th>Fare Stage</th>
<th>Location</th>
<th>Fare</th>
</tr>";
while($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)){
echo"<tr>";
echo"<td>".$x."</td>";
echo"<td>".$row['location']."</td>";
echo"<td>".$row1['fare']."</td>";
echo"</tr>";
$x++;
}
echo"</table>";
}

What you really want is to not only store the visual data in your table but also some sort of meta data. There are several ways to achieve this.
Method #1: (ab)use the id or class attributes:
The resulting HTML would look like this:
<!-- example with the id-attribute: -->
<tr id="mysql_row_1"> ... </tr>
<tr id="mysql_row_2"> ... </tr>
<!-- example with the class-attribute: -->
<tr class="mysql_row_1"> ... </tr>
<tr class="mysql_row_2"> ... </tr>
This would both generate valid HTML but you would abuse attribute-tags for a purpose they're not implemented for, what is generally regarded as bad. Imagine if you had to store more than just one value. You could assign multiple classes, but you'd get stuck with the id-tag then. Therefore: don't do this!
You'd have to change your code like this to achieve this solution:
(I assume you want the value of $x as the rownumber.)
while ($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)) {
echo '<tr class="mysql_row_'.$x.'" onclick="getRowNumber()">';
echo "<td>".$x."</td>";
echo "<td>".$row['location']."</td>";
echo "<td>".$row1['fare']."</td>";
echo "</tr>";
$x++;
}
The javascript part:
function getRowNumber() {
var rowNumber = this.className.replace("mysql_row_",""); // fetches the classname and removes the extra-strings
alert(rowNumber); // alerts "1", "2", ...
}
Method #2: Use the data-* attributes:
This solution is valid for HTML5. Please add additional information regarding compatibility if you have some.
Your HTML Code will look like this:
<tr data-mysql_row_number="1" onclick="getRowNumber()"> .... </tr>
<tr data-mysql_row_number="2" onclick="getRowNumber()"> .... </tr>
And the modified javascript:
function getRowNumber() {
alert(this.getAttribute("data-mysql_row_number")); // alerts "1", "2", ...
}
This also generates perfectly valid HTML(5) code and lets you store infinite endless amounts of information since you can specify as many data-* attributes as you want to.
Method #3: use invisible <input> fields:
The resulting HTML code:
<tr onclick="getRowNumber()">
<td>
Normal content of this field
<input type="hidden" name="mysql_row_number" value="1"/>
</td>
</tr>
And the JS code to fetch the values:
function getRowNumber() {
var rowNumber = this.getElementsByName('mysql_row_number')[0].value;
alert(rowNumber); // alerts "1", "2", ...
}
This as well produces valid HTML but is semantically not really correct in my opinion, since the data inside the <input> fields is some kind of loose and not directly connected to the row. Plus you can make multiple <input> fields with the same name.
I would suggest method #2 ( data-* ), as this is the most flexible solution and uses an attribute that has been designed to store meta-data.
Method #1 would work the most reliable across all (older) browsers since all of them support acces to the id or class attribute via JS, as long as you keep the id tag unique.
Method #3 will also be quite reliable with older browsers.

Instead of echo"<tr>"; do :
echo "<tr id='row_".$row['id']."'>";
then when a tr is clicked, just retrieve $(this)[0].id like that with jQuery inside a script tag (be sure jQuery is included, it's a powerful JS library, google it for additional informations) :
<script>
$("#my_table").on("click", "tr", function(){
alert($(this)[0].id.replace("row_", ""));
});
</script>

Related

Getting id from a textarea in a while loop in PHP for updating in mysql

I have a table where is one week displayed (each row is one day).
I get the rows from a while loop from my database. The rows are displayed in bootstrap accordions.
There is a textarea in every accordion row where the user can input (update) some text.
I want to update this text into my database. It should update the text depending on the day id.
<form method="POST" action="">
<table class="table table-hover" style="border-collapse:collapse;">
<thead>
<tr>
<th>Weekday</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
// Select Statement (for shortening not included into this Stack question)//
while($row = $statement->fetch()) {
$thedate = $row['Date'];
$weekday=strftime("%A", strtotime($thedate));
$date=date('d-m-Y', strtotime($thedate));
echo "<tr data-toggle='collapse' data-target=#".$row['Date']." class='clickable collapse-row collapsed'>";
echo "<td >".$weekday."</td>";
echo "<td>".$date."</td>";
echo" <td style='color:black; font-size:20px;'><i class='fas fa-angle-down'></i></td>";
echo "</tr>";
echo "<tr><div class='accordian-body collapse' id=".$row['Date'].">
<td colspan='1' class='hiddenRow'><textarea name=".$row['id']." rows='5' cols='80'>".$row['Text']." </textarea></td>
//the $row['id'] should give every textarea a unique dayid from my database
echo"</td>
</div></tr>";
}
if(ISSET($_POST['id'])){
$debug=$_POST['id'];
}
var_dump($debug); // var_dump for debugging. See text below
?>
</tbody>
</table>
<button type="submit" name="Speichern" class="btn btn-lg btn-primary btn-block">Speichern</button>
</form>
Before writing the Sql Update Statement I wanted to debug to find possible bugs.
If i debug this with var_dump I get the error message "Undefined variable $debug" and I dont know why. The variable shouldnt be empty because in the textareas is always text.
Im new to PHP and coding at all so probably Im making a dump mistake.
EDIT: If I put the var_dump inside the if condition i get nothing as return.
I tried it also with the var_dump in the if block but then i get nothing as return.
That’s because you do not have any form field that is actually named id. You put name=".$row['id']." on your textarea, and that is likely a numeric value. And you probably don’t know which one that will be, on the receiving end.
Plus, since you are creating multiple such fields in a loop, PHP will overwrite all values for this parameter with the last one. You need to use a naming scheme that includes square brackets to avoid that, something like name="foo[]" - then $_POST['foo'] will become an array that you can loop over.
And since you will still need your record ID to associate with the data, you can put that into the brackets, name="foo[123]" – then this 123 will become the key of that array element, for this specific textarea.
If you loop over that using the extended foreach syntax, then you have easy access to the ID, and the value entered by the user:
foreach( $_POST['foo'] as $id => $value ) { … }

New lines HTML if value changed in MySql Output via PHP

This is the HTML/PHP , I am using to display some data.
<body>
<section>
<h1>Facebook Search</h1>
<!-- TABLE CONSTRUCTION-->
<table>
<tr>
<th>Comment</th>
<th>Comment Made By</th>
<th>Commentor's Profile Link</th>
<th>Comment ID</th>
<th>Post ID</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS-->
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!--FETCHING DATA FROM EACH
ROW OF EVERY COLUMN-->
<td><?php echo $rows['comtext'];?></td>
<td><?php echo $rows['comby'];?></td>
<td><?php echo $rows['compro'];?></td>
<td><?php echo $rows['commentid'];?></td>
<td><?php echo $rows['postid'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>
</html>
and I am getting the data like this from the db.
$sql = "SELECT comments.*, posts.postid FROM comments JOIN posts USING(postid)";
$result = $mysqli->query($sql);
$mysqli->close();
This outputs a single table with all the data. My question is , is there a way to break the single table into tables when the value of postid changes? It goes like..is 1 for x number of rows, then 2 for x number of rows and so on. I wanted to have a little break between those tables.
is there a way to break the single table into tables when the value of postid changes
You should stop using "SELECT *", it's inefficient and makes code difficult to maintain. While we're talking about style here, you swap back and forth between PHP and inline HTML which also impacts the readability of your code.
As to your question...
You need to ensure that the output of your query is sorted by postid - or you're going to get a lot of tables.
Use a state variable to track the postid from the previous iteration of the loop.
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
The problem with this is that each iteration of the expects that you've already written <table> to the output stream - including the first iteration. You could do this before the loop - but you'll end up with an empty table at the top of the page. You could add another state variable to track whether you have opened a table tag yet. Personally, I'd go with making inferences from the value of the existing state variable:
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
$prev || close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
(the || is a quick way of writing if (not(condition)) do something() )
Note that unless you fix the size of the columns, then each table will be independently sized to fit the data that resides within it.

php search won't clear when javascript onclick is clicked

So this is what I have - A javascript onclick event that will parse json from my MySQL database data and display it when someone clicks on a seat.
var jsonData = <?php echo json_encode($array); ?>;
function displayInfoForDiv(i){
document.getElementById('fname').innerHTML = jsonData[i].first_name;
document.getElementById('lname').innerHTML = jsonData[i].last_name;
}
Output
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span id="fname"><?php echo $row['first_name']; ?></span></p>
<p><span id="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
The PHP is for my search box when you try to look up a name - I'm using this
$sql = mysql_query("select * from people where first_name like '%$term%' OR last_name LIKE '%$term2%'");
So the problem I'm having is when I conduct a search for Matt, more then one result will show up. Say:
Matt
Hasselbeck
Matt
Hew
But if I use the onclick event and click on joe's seat, it will display like this:
Joe
Frill
Matt
Hew
So the problem is that the search results will remain when I trigger the onClick event but the first one will change.
My question is, is there a way when I click on a seat to clear the search results and only display the one but when I conduct a search to display the similar names.
I'm using the PHP and JS to call the same data because, the JS only has a range of floor, while the php is grabbing everything from the database.
Hopefully this is clear and thank you for any input.
You Have Two Issues going on here.
You are using the same value for the id attribute multiple times.
Your result setup is logically flawed
Solution to Issue 1
Change id attribute to class attribute
When you use document.getElementById in javascript it returns the first element with that id.
Which means that if you have multiple ids with the same value only the first element will be selected. So your function should be changed to the following
function displayInfoForDiv(i){
document.getElementsByClassName('fname')[i].innerHTML = jsonData[i].first_name;
document.getElementsByClassName('lname')[i].innerHTML = jsonData[i].last_name;
}
Solution to Issue 2
Use template for results
Wrap all results in a div tag
By wrapping results into a div tag you will be able to clear results by clearing the html for that div tag.
<div id='Results'>
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span class="fname"><?php echo $row['first_name']; ?></span></p>
<p><span class="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
</div>
<script>
function clearResults()
{
document.getElementById('Results').innerHTML='';
}
</script>
To use a template for results I would recommend underscore.js
So a template for your needs would look like the following:
<script id='result-template' type="text/x-jquery-tmpl">
<p><span class="fname">${first_name}</span></p>
<p><span class="lname">${last_name}</span></p>
</script>
And to utilize the template you would do the following:
The code below assumes you have included underscore.js
function LoadResults(jsonData)
{
_.templateSettings = {
interpolate: /\$\{(.+?)\}/g
};
var output='',
resultDiv=document.getElementById('Results');
template= _.template(
document.getElementById('result-template').innerHTML
);
clearResults();
for(x in jsonData)
{
resultDiv.innerHTML+=template(jsonData[x]);
}
}

how to get an id of an element, which is returned from php code

I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);

Disable multiple checkboxes with javascript

I've got a problem with my JS function. I'll explain that to you with my code and a Prt Sc.
Code = http://jsfiddle.net/dKeRf/
This is a Php function and JS function.
Screen = http://img824.imageshack.us/i/antoe.png/
If one of the 2 checkbox over the table is checked, all the checkbox in the two table must be disabled. For the moment It works for the first checkbox, but not for the second, and I ask you why ? :)
I use '10' in my 'For' jut for a test, I'll change that latter by the number of row of the table.
Thanks for your help and have a good day !
Add a class to all of the checkboxes:
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
Then use jquery to update all of the checkboxes at once:
<script>
$(document).ready(function(){
$(".selectAll").click(function() {
if($(".selectAll").attr("checked")) {
$(".the_checkbox:checkbox").attr("disabled", true);
} else {
$(".the_checkbox:checkbox").removeAttr("disabled");
}
});
});
</script>
UPDATE: Changes the answer to use the .class name for updating the checkboxes instead of the ID so that the ID can remain unique and conform to HTML standards.
IDs are not allowed to start with a number, they must start with a letter. So document.getElementById(1234) will fail (I think IE might not say anything and allow it, but FF doesn't work). You should be ok with just putting a letter in front of the number and change the getElementById to document.getElementById('cb'+id2);.
Also, just a side note, if you are passing in this to a function onClick, that parameter is a reference to the element that was clicked. So there is no need to get box.id and then do document.getElementById(checkId). technically document.getElementById(checkId) is === box so you could just say box.checked.
http://www.w3.org/TR/html4/types.html#h-6.2. This is the spec that talks about ID attribute naming requirements:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Edit:
Even better than using document.getElementById() to select each checkbox, would be to use document.getElementById() on a parent element that the checkboxes you want to disable share (such as the table they are in) and then use document.getElementsByTagName('input') to get a collection of all the checkboxes and loop/disable them with that. So the JS disable code would look like:
Some table:
<input type='checkbox' onClick='checkCBs(this,"someTable1");'>
<table id='someTable1'>
<tr>
<td>This is checkbox 1:</td>
<td><input type='checkbox' name='group1' value='checkbox1'></td>
</tr>
<tr>
<td>This is checkbox 2:</td>
<td><input type='checkbox' name='group1' value='checkbox2'></td>
</tr>
</table>
The code:
function checkCBs(box, parent){
var parent = document.getElementById(parent),
CBs = parent.getElementsByTagName('input'),
i;
//loop through all input elements
for(i=0;i<CBs.length;i++){
//make sure the input is a checkbox
if(CBs[i].type && CBs[i].type=='checkbox'){
//set disabled on this checkbox to opposite
//of whether box is checked.
CBs[i].disabled = !box.checked;
}
}
}

Categories