Changing style of all same class name of elements using javascript - javascript

I got this error. And I can't find what was wrong with it. I am using PHP and javascript.
I have a hidden iframe below my code:
<iframe id="hidden_form_submitter" name="hidden_form_submitter" style="width:100%;height:1px;visibility:hidden"></iframe>
And I have this line of code, an action button in which the id of a row will send as URL parameter:
<tr bgcolor="#d1ffcf" class="row-<?=$transaction['id']?>">
<td>
<a class="done-btn" data-confirm="Are you sure?" href="?action=change&status=done&transact_id=<?=$transaction['id']?>" target='hidden_form_submitter' title="Click if matched!"> Done</a>
</td>
</tr>
Then lastly I have this code on top to update the row in my database:
<?
if($_GET['action'] == 'change'){
//update query here
echo "<script>window.parent.document.getElementsByClassName('row-{$get['id']}').style.backgroundColor='green';</script>";
exit;
}
?>
No problem on the updating side in my server.
The problem is the JavaScript wherein I want to change the bgcolor of all same class without reloading the whole page.
UPDATE: Cannot change the background of every class. Example, I have this parameter to be send. ?action=change&status=done&transact_id=1608
So all element with class row-1608 should change the background color or change something style.

Try changing this:
echo "<script>window.parent.document.getElementsByClassName('row-{$get['id']}').style.backgroundColor='green';'</script>";
To this:
echo "<script>";
echo "var allRows = window.parent.document.getElementsByClassName('row-{$get['id']}');";
echo "for (var i = 0; i < allRows.length; i++) {";
echo " allRows[i].style.backgroundColor = 'green';";
echo "}";
echo "</script>";
You need to iterate allRows and set the backgroundColor on each element.
(Inspired by this example)

Related

Change of div in the same page without refresh

In one of my pages, I have an <a> tag. When I click it, I am passing the variable as a GET parameter and retrieving it in the same page and displaying the details.
The code to get the parameters:
if(isset($_GET['CatId']))
{
$CatId= $_GET['CatId'];
}
else $CatId=0;
if(isset($_GET['MainProductId']))
{
$MainProductId= $_GET['MainProductId'];
$FilterAllProductQuery ="WHERE Product.MainProductId = '$MainProductId'";
$FilterProductQuery = "AND Product.MainProductId = '$MainProductId'";
}
else
{
$MainProductId=0;
$FilterAllProductQuery="";
$FilterProductQuery="";
}
The <a> tag:
<a href='Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>' ><?php echo $row["MainProdName"] ?></a>
The details to be displayed:
if($CatId == 0)
{$sql = "SELECT *,Product.Id AS ProdId, Product.Name as ProdName FROM Product $FilterAllProductQuery ";}
else
{$sql = "SELECT * ,Product.Id AS ProdId, Product.Name as ProdName FROM Product INNER JOIN MainProduct ON MainProduct.Id = Product.MainProductId
INNER JOIN Category ON Category.Id = MainProduct.CategoryId WHERE Category.Id = '$CatId' $FilterProductQuery ";}
$result1 = $dbcon->query($sql);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$id = $row["ProdId"];
// $image=$row["ImagePath1"];
$qty = $row["Quantity"];
?>
<li class="col-lg-4">
<div class="product-box">
<span class="sale_tag"></span>
<div class="row">
<img src='themes/images/<?php echo $row["ImagePath1"]; ?>' height='200' width='250'> </a></div></div></li>
Now the code is working fine, but what's happening is that when I click the <a> tag, as I am passing the get parameters, the page is refreshing. As all the code are on the same page, I don't want the page to be refreshed. For that, I need to use Ajax request. How can I do that?
I would make an onclick() event on the a tag like so:
<?php echo '<a c_id="'.$CatId.'" MainProductId="'.$id.'" onclick="sendProduct()">'.$row["MainProdName"].'</a>';
Afterwards i would in a .js file write a simple function called sendProduct() and inside i would do an ajax request to a page named ex: insertproduct.php, get the information back and Insertproduct.php would process the data and you could use .html() or .append() to assign the data to the div showing the data with a normal id.
The c_id, MainProductId are custom attributes you could recieve in the .js file as $("#youraTag").attr("c_id");
There's a really good guide here on basic ajax: https://www.youtube.com/watch?v=_XBeGcczFJo&list=PLQj6bHfDUS-b5EXUbHVQ21N_2Vli39w0k&index=3&t=1023s
First you have to remove the href of the link and give it an id.
<a id='link'>
<?php echo $row["MainProdName"] ?>
</a>
Then you put this jQuery into your page. Note, you need to have a div in which you are going to put in all your obtained results. I reffered to this div in the code as #mydiv.
$("#link").click(function(){
$("#mydiv").load("Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>");
});

How to overcome of passing single static value to the function?

I'm displaying as many buttons as the number of rows in query. Every row has it's own names & properties. When i click on any of the buttons, it should pass that particular value to the function. But, when i tried with the following code, it only passes very first value if i click on any buttons.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change()' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change()
{
var elem = document.getElementById("myButton1");
alert(elem.value);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".elem.value."</td></tr></table>"; ?>
}
</script>
How do make it passing dynamic values (clicking upon any buttons, it should pass it's corresponding value) ?
id values must be unique in HTML. Having multiple elements with the same id is invalid and will not work as desired.
You don't need ids at all. Instead, the minimal change is to pass this into your function:
<button onclick='change(this)' ... >
and in your function
function change(btn) {
alert(btn.value);
}
But the real answer is don't use onclick attribute event handlers. They're a mid-1990's technology. Things have moved on in 20 years.
In this case, I'd use a delegated handler on the container all these figures are in. There's probably a container nearer to them that you can use, but in the worst case, you can use document.body:
Put a common identifying feature on the buttons (say, a class), then:
$(document.body).on("click", ".the-class", function() {
alert(this.value);
});
One handler handles all the buttons, since click bubbles.
Again you probably want a container closer to the list of figures, rather than document.body.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change(this.value)' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change(button_val)
{
alert(button_val);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".button_val."</td></tr></table>"; ?>
}
</script>

how to save click counts from multiple links ,on a dynamic table to a database

i have a dynamic table that has a list of records, basically for all rows of the table there is a link to click, that passes the id of that row clicked to the next page,
my question is how can i save and display the number of times each link have been clicked ?
here is my code
<table width="100%" >
<tr bgcolor="#FF3399" style="color:#FFF">
<td><h3><strong>Topic</strong></h3></td>
<td><h3>Author</h3></td>
<td><h3>Date</h3></td>
<td><strong>Replies</strong></td>
<td><strong>Views</strong></td>
</tr>
<?php do { ?>
<tr bgcolor="#009900" style="color:#FFF">
<td><h4><a style="color:#FFF" onclick="spinn();" data-ajax="false" href="send.php?id=<?php echo $row_forum['id']; ?>"><strong><?php echo $row_forum['Topic']; ?></strong></a></h4></td>
<td bgcolor="#009900"><h4><?php echo $row_forum['Author']; ?></h4></td>
<td><h4><?php echo date("g : i a, j/F/Y,",strtotime($row_forum['Date'])); ?></h4></td>
<td> <?php echo $row_forum['Replies']; ?></td>
<td><?php echo $row_forum['Views']; ?></td>
</tr>
<?php } while ($row_forum = mysql_fetch_assoc($forum)); ?>
</table>
On the page that is the target of your link, simply invoke a method which will increase your count field in the database. You can put code like this in your target page:
<?php
function increaseCount() {
// ... connect to db
mysql_query('UPDATE table SET count=count+1 WHERE id='.$id);
}
increaseCount($_GET['id']);
?>
Please note, that the above code is very trivial and dangerous and only shows the concept. It does not protect you from SQL Injection at all. Doesn't even check, if the id parameter in the address exists.
Also, don't use methods like mysql_query - they're depracated.
Alternatively, try using Ajax to change the behavior of link's click event - send an ajax request to PHP script which will increment your count field in the database, and then follow your link's href :)
XmlHttpRequest
jQuery.ajax
Edit
$topicId = $_GET['id']; // you need to change 'id' to the name of your ID-parameter in the URL
$viewsIncrementQuery = "UPDATE `topic` SET `Views` = `Views` + 1 WHERE `id` = " . $topicID;
$incremented = mysql_query($viewsIncrementQuery, $epl) or die(mysql_error());
You need to put that code somewhere close to where you extract data from the database, so probably after the $query_lin = sprintf( (...) part.
If it throws an error - show it's message.

Ignoring links, checkboxes.. in an editable html field using jquery

Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out

How do I create links in the cells of a PHP generated table?

I have a table generated from some PHP code that lists a SMALL amount of important information for employees. I want to make it so each row, or at least one element in each row can be clicked on so the user will be redirected to ALL of the information (pulled from MySQL database) related to the employee who was clicked on. I am not sure how would be the best way to go about this, but I am open to suggestions. I would like to stick to PHP and/or JavaScript. Below is the code for my table:
<table>
<tr>
<td id="content_heading" width="25px">ID</td>
<td id="content_heading" width="150px">Last Name</td>
<td id="content_heading" width="150px">First Name</td>
<td id="content_heading" width="75px">SSN</td>
</tr>
<?php
$user = 'user';
$pass = 'pass';
$server = 'localhost';
$link = mysql_connect($server, $user, $pass);
if (!$link){
die('Could not connect to database!' . mysql_error());
}
mysql_select_db('mydb', $link);
$query = "SELECT * FROM employees";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr class=".$class.">";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
echo "</tr>";
}
?>
</table>
EDIT
Ok, after modifying what #DrColossos posted I have been able to get my links to work correctly, but now I'm having trouble with the uniqueness part. Below is the code I am now using to create my table:
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
This makes all of the elements of a row hyperlink to Edit_Employee.php?**id**. For instance if the id was one the hyperlink would be Edit_Employees.php?1. Now what do I need to do in my Edit_Employee.php page to get or recognize the id in the link, because it is that id that is unique and that is what I need to base my MySQL search on.
EDIT
Figured it out. This did the trick:
$id = $_GET['id'];
I found that creating my links as I did makes the id a global variable which PHP can pull from the hyperlink. I used the code above in the page that the hyperlink points to and I was able to get what I wanted. Not too hard, but frustrating if you don't know how it is done!
You can already create an unique link with the "ID" of each employee.
You could do the following:
echo "<td><a href="employee.php?id=\"" . $row['id'] . "\">" . $row['id'] . "</td>";
or more readable
echo "<td><a href="employee.php?id=\"{$row['id']}\">{$row['id']}</td>";
Then you can use the employee.php to display it's detail (the id will be in $_GET['id'], see here). Don't forget to check the value of $_GET['id'] before you process it, since it can contain harmfull data (e.g. SQL-Injection).
BTW, the HTML attribute 'id' that you use in the table id="content_heading" is supposed to be unique on the site, just as a site note.

Categories