getting the id of looping element when clicked on jquery - php

I am taking list of data from my database using a loop. I loop one div but the values change depending on what I have in the database. I will want to get the id of the link that i click on from the individual divs. below is my html codes...
<?php
$query = $student->conn->prepare('SELECT * FROM groups');
$query->execute();
$result = $query -> fetchAll();
$count = 0;
foreach ($result as $row) {
$count = $count + 1;
$groupName = $row['GpName'];
$groupAdmin = $row['GpAdmin'];
$groupPurpose = $row['GpPurpose'];
$output = "42";
echo "<div class='animated flipInY col-sm-4'>
<div class='tile-stats'>
<div class='icon'><i class='fa fa-tags'></i></div>
<div class='count'>$count</div>
<h3 id='groupName'>$groupName</h3>
<a id='$groupName' class='display' href='#'><p>Click here display group information.</p></a>
</div>
</div>";
}
?>
This is the jQuery code I use. it works in the console but it doesn't work on the page:
$('.display').on('click', function () {
$(this).next();
var id = $(this).prev().val();
alert(id);
});

The statement
It works in the console but it doesn't work on the page
makes me think you are using Ajax so that means you are binding an event to elements that do not exist. So use event bubbling or bind the events after you replace the content.
$(document).on('click', '.display', function () {
var id = $(this).prev().val();
alert(id);
});

Related

Modal image only working on 1 image

I would like to understand why my modal image is only working on the 1st image on my page. and not all of them in the array.
I have attached the Script, CSS and HTML as well as a link to the site.
http://jarrettonions.co.za/
Thanks for the help
Dylan
<script>
var modal = document.getElementById('myModal');
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
</script>
Html for the Images
<?php
require 'connect.php';
$sql = "SELECT * FROM art ORDER BY hits DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<img id='myImg' src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]." • ".$row["year"]." • ".$row["type"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."' height='auto' width='100%'/>
<div id='myModal' class='modal'>
<span class='close'>×</span>
<img class='modal-content' id='img01'>
<div id='caption'></div>
</div>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
Then for the index page it just calls the art.php file and contains the Script
Having same ID multiple times is not valid html according to the W3C specification.
jQuery uses document.getElementById method, which returns only the first element with that ID.
So, you should never have two elements on the same page with the same ID. If you need it use a 'class' instead.
Just take a 'class' instead of 'id' in your img tag
and use document.getElementsByClassName instead of document.getElementById in your javascript.
Hope it will help you.

applying "this" jQuery, to delete an echoed row in php from sql database

This is my current plan:
Clicking on a row selects or gets the id of the row, then this id is passed to a delete script most likely via AJAX or an HTTP request. The problem I have is how to identify the row from the click using "this" this as in show below:
$( this ) {
// get id and send to delete script
}
I have echoed out the rows so that I have the id row
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'dbconnect.php');
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT COUNT(*) FROM entries";
if ($result = $link->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
if($row[0]==0){
echo "There are no entries.";
}else {
$query2 = "SELECT id,saying,date,thumbs_up,comments FROM entries ORDER by ID ASC ";
if (($result = $link->query($query2))) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo
'<div class="container" align="center"">'.
'<div class="entry-container" align="left">'.
$row[1]." ".
'</div>'.
'<div class="x" align="center">'.
'<button class="red" name="remove" onclick="remove_entry();">remove entry'.
' '.
$row[0].
'</button>'.
'</div>'.
'</div>'.
'<br>'
;
}
}
}
}
/* free result set */
$result->close();
}
?>
remove_entry(); doesn't do anything yet, presumably it will send the id to the delete script which then removes the row using the DELETE command
<script type="text/javascript">
function remove_entry() {
var answer = confirm("Delete this entry?")
if (answer){
//some code
}
else{
//some code
}
}
</script>
What is the most direct and effective / efficient way to do this?
I would even prefer not to show id, just use a simple x for the delete button, I echoed the id so that I had it to use to identify the row to be deleted.
Using jQuery can do :
HTML
<div class="entry-container" align="left" id="'.$row[0].'">
JS
$(function(){
$('button.red').click(function(){
var $row = $(this).closest('.entry-container'),
rowId = $row.attr('id');
$.post('/path/to/server', {id: rowId}, function(resp){
if(resp =='ok'){
$row.slideUp(function(){ $row.remove() });
}
});
});
});
Then remove your inline onclick
In PHP receive the id with $_POST['id'] and validate it before passing to db query
For starters, don't use 2 SQL queries. Just do the one you use to get data and, if it has no rows, give a different output.
Use semantic markup like so:
'<button type="button" class="remover" id="entry-' . $row[0] . '">remove this entry</button>'
Then in your jQuery, use something like this:
$(function() {
$('.entries').on('click', '.remover', function() {
var eId = this.id.replace(/^\D+/, '');//since IDs should not start with a number
$.post(
'/your/delete/endpoint/',
{
id: eId
},
function(data) {
if (data.ok) {//sending JSON responses are easier to debug and you can add to them later without breaking things
//remove row
}
else {
//display error message
}
}
);
});
});
The second parameter to on() makes it a delegated event, which means you can add new items to an existing set, with the same remover markup, and the new remove buttons will also work.

JSON data in HTML page in a table

I struggling print all my data from DB to webpage using JSON.
But I not understand logical how it should work.
My JSON script:
<script>
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});
</script>
And test1.php file
<?php
require_once 'connection.php';
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
$sql -> execute();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values = array('code'=>$row['code'],
'line'=>$row['line']);
}
echo json_encode($values);
?>
and part of HTML:
<body>
<table id="div-my-table">
</table>
</body>
And system return back only:
<table>
undefined undefined
undefined undefined
First make below correction in your code
$values[] = array('code'=>$row['code'],'line'=>$row['line']);
Above change will append all database value to $value variable and will show all records instead of last record of db
Also Please check with your table name in below query
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
It seems that you are taking db name constant here instead of table name as mentioned below.
$sql = $conn -> prepare("SELECT * FROM TABLE_NAME");
If you're expecting multiple rows, you need to gather the results properly. The $values gets overwritten every iteration.
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// add another dimension
$values[] = array(
'code'=>$row['code'],
'line'=>$row['line']
);
}
echo json_encode($values);
Or for just one line:
echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));
So that they are properly nested.
Then on your JS:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("test1.php", function(data) {
var table_rows = '';
$.each(data, function(i, item) {
table_rows += "<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").html(table_rows);
});
});
</script>
You're overwriting the same $values variable each time through the loop. At the end, it will just contain a single row, not an array of all the rows. You need to add each row to $values, not replace it. It should be:
$values = array();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values[] = $row;
}
echo json_encode($values);
Also, your jQuery is wrong. You shouldn't use .text() when you're creating HTML, you should use .html(). And you don't need to append </table> -- these functions operate on the DOM, not the HTML, and the DOM always has complete elements.
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
var table = $("<table>");
$("#div-my-table").empty().append(table);
$.each(data, function(i, item) {
table.append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
});
});
Use last.after();
Instead of append();

Jquery - Onclick insert div into subdivs

The following function appends on-click a div containing an image, to each main div from the "edit" class.
I need to insert on-click a div into each subdiv from c.$k class. All the sub-divs from c1/c2 class have unique ids.
Basically I need to display a rrdtool created graph inside each sub-div which represents a device with unique IP. (the id of the sub-div)
In other words I need to get the id from each class c.$k div and use it as 'ipx' on var y,
then insert a new div class='graph' into each class c.$k div. So we can ignore the second parameter from my function (ipx) as it's not relevant. I need to use the "children" ids from div class='edit'.
This is the first time when I'm using jquery and any help is more than welcome.
function edit_mode(idname,ipx) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
// var subdivid = $("#idname").children("div");
var y = 'http://domain.com/index.php?ip='+ipx;
$("#"+idname+" img:last-child").remove();
$("<div class='graph'><img src='"+y+"'></div>").appendTo(x);
};
The PHP code:
$k=1;
$t="";
while($row = mysql_fetch_array($result)){
if ($row['id'] != $t) {
if ($t != "") {echo "</div>";}
echo "<div onclick=\"edit_mode('".$row['idDevice']."','".$row['IP']."')\">".$row['name']." ".$row['IP'] ."</div><br><div class=\"edit\" id=\"".$row['idDevice']."\">";
$t = $row['id'];
$k = 1;
}
echo "<div id=\"".$row['IP']."\" class=\"c".$k."\"><form method=\"post\" action=\"edit.php?idDevice=".$idDevice."\">";
.................................................................
echo "</form></div>";
$k = 1+($k % 2);
}
I've done this:
function edit_mode(idname) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
var subdivid = $.map($('#idname > div'), function(child) { return child.id; });
var y = 'http://domain.com/index.php?ip='+subdivid;
$("#"+idname+" img:last-child").remove();
var el = document.createElement('div');
el.className="graph";
el.innerHTML = '<img src='+y+'>' ;
document.getElementById(subdivid).appendChild(el);
This is doing exactly what I want, except that is working for one parent div with one child. The question would be now: how can I modify this function to work when I have dynamically created arrays of divs (idname) with children (subdivid).
Thank you
From what I can see the second parameter to edit_mode is the id of the sub div with class c.$k, so you can use it for appending the div with image
function edit_mode(idname,ipx) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
// var subdivid = $("#idname").children("div");
var y = 'http://domain.com/index.php?ip='+ipx;
$("#"+idname+" img:last-child").remove();
$("<div class='graph'><img src='"+y+"'></div>").appendTo('#' + ipx);
};

cannot click items echoed by another page using ajax - $(document).on is not working

updated
i'm having 2 pages. An index page connected to a js file. This js file containing ajax code fetching data from database.
this is my js file
$(document).ready(function() {
// getting links from db andshow sub_menu div //
$(".menu_item").mouseover(function(){
$(this).addClass("selected").children().slideDown(500,function(){
var id = $(".selected").attr("id");
var ajax= false;
ajax = new XMLHttpRequest();
var qst = "?id="+id;
ajax.open("GET","ajax/get_sub_cats.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
$(".sub_menu[title="+id+"]").html(ajax.responseText);
}
}
ajax.send(null);
});
});
// hiding sub_menu div //
$(".menu_item").mouseout(function(){
$(this).removeClass("selected").children(".sub_menu").slideUp(500);
});
// keeping sub_menu div visible on mouse over //
$(".sub_menu").mouseover(function() {
$(this).stop();
});
// clicking sub menu link in the menu //
$(document).delegate("a#subCatLink","click",function(){
alert("test");
});
// document ready end
});
and this is get_sub_cats php file used to fetch links from db
<?php
require('../_req/base.php');
$id = $_REQUEST['id'];
$getSubcatsQ = "select * from sub_cats where Main_Cat_ID = '$id'";
$getSubcatsR = mysql_query($getSubcatsQ);
$numrows = mysql_num_rows($getSubcatsR);
while($row = mysql_fetch_array($getSubcatsR)){
?>
<a id="subCatLink" href="products.php?id=<?php echo $row['Sub_Cat_ID']; ?>"><?php echo $row['Sub_Cat_Name']; ?></a><br />
<?php
}
mysql_close($connect);
?>
clicking links coming from the other php file using ajax is not working at all
Sorry, maybe this will help, maybe not. But...
Why don't you use something like this:
jQuery
$(".menu_item").mouseover(function(){
var id = $(".selected").attr("id");
var qst = "?id="+id;
var html = '';
$.getJSON('ajax/get_sub_cats.php'+qst, function(data){
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<a id="subCatLink'+data[i].Sub_Cat_ID+'" href="products.php?id='+data[i].Sub_Cat_ID+'">'+data[i].Sub_Cat_Name+'</a>';
}
$(".sub_menu[id="+id+"]").html(html);
});
});
PHP
require('../_req/base.php');
$return = array();
$id = $_REQUEST['id'];
$sql = "select * from sub_cats where Main_Cat_ID = '$id'";
$result = mysql_query($sql);
while($ln = mysql_fetch_array($result)){
$return[] = $ln;
}
echo json_encode($return);
ok try this
$(document).delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
});
That should, as a test, show the href for every link on your page. If that works, put all the links you want to show in a div. Then call it with
$('#divID').delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
})

Categories