Modal image only working on 1 image - php

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.

Related

PHP not displaying server results online

We have built this online prototype and it worked just perfectly on our local environment, but after moving it online, some buttons and a table are not working. The buttons are all buttons that, have conditions to only show if eg. the user is logged in or has a certain user type (in this case a tutor). The table is not showing the search results.
It's possible to register a user and also login, but when entering the subpages, only logout, search button and logo is responding. And we can see that user are being saved in our database.
Can anyone give a hint to what it is we do wrong? I've displayed one of the buttons code here below.
HTML:
<ul>
<li><a class="modal-button modal-button-user" data-modal="modalEditUser"><i class="far fa-user"></i> Hello <?php echo $_SESSION["firstName"];?>!</a></li>
<li>
<form action='_home.php' method='post'><button class="logout_button" type="submit" name="logOutBtn" id="logOutBtn">Log Out</button></form>
</li>
</ul>
JS:
var modalBtns = [...document.querySelectorAll(".modal-button")];
modalBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.getAttribute('data-modal');
document.getElementById(modal).style.display = "block"
}
});
var modalBtnsTutor = [...document.querySelectorAll(".modal-button-tutor")];
modalBtnsTutor.forEach(function(btn){
btn.onclick = function() {
var modal = btn.getAttribute('data-modal');
document.getElementById(modal).style.display = "block"
}
});
var closeBtns = [...document.querySelectorAll(".close")];
closeBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.closest('.modal');
modal.style.display = "none";
}
});
window.onclick = function(event) {
if (event.target.className === "modal") {
event.target.style.display = "none";
}
}
PHP:
<?php
require 'config.php';
//try to make logout/login/welcomeMessage appear/disappear whether you're
logged in or not
if (isset($_SESSION["userID"])) {
echo "<script>
window.onload = function() {
document.getElementById('navUser').style.display = 'block';};
</script>";
$go = "home.php";
} else {
echo "<script>
window.onload = function() {
document.getElementById('navVisit').style.display = 'block';};
</script>";
$go = "index.php";
}
?>

getting the id of looping element when clicked on jquery

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);
});

when i add new comment the delete button doesn't work till i reload the page?

first page
ajax and jquery code
<script>
$(document).ready(function(){
$(".delete_buttom").click(function(){
var x = $(this).attr('id');
click_delete(x);
});
function click_delete(commentId){
$.post("ajax_comments3.php",
{
task : "this is the task",
commentId : commentId
}).success(
function(data){
$('#comment_' + commentId).remove();
}).error(function(){
alert("404 not found");
});
}
</script>
======================================================================
second page code
<?php
if(isset($_POST['task']) && $_POST['task'] == "this is the task"){
$server_id = $_POST['ajax_id'];
$server_comment = $_POST['ajax_text'];
$user_name = $_POST['ajax_uname'];
$connection = mysqli_connect("localhost","root","","comments")
$insert_query = "insert into comment (commet_text,user_id)
values ('$server_comment','$server_id')";
$excute_insert = mysqli_query($connection,$insert_query) or die("insert query error");
?>
this the the li tage which will insert into ul tage (i have a ul tage in html code)
<li class="li_style" id="comment_<?php echo mysqli_insert_id($connection) ?>">
<img src="profile.jpg" class="user_img_src" />
<h5 class="username"><?php echo $user_name ; ?></h5>
<div class="delete_buttom" id="comment_<?php echo mysqli_insert_id($connection) ?>">X</div>
<div class="user_comment"><?php echo $server_comment ; ?> </div>
</li>
<?php
}
?>
when i type a new comment it inserted into database and appear in the web browser as well but the problem is that i have a delete button when i clicked on it right after typing comment it doesn't work i have to reload the page the the delete button works fine any solutions.
Correct. That is because theres no event on that new button.
Maybe like this:
var deleteButton = function() {
$(".delete_buttom").off('click');
$(".delete_buttom").on('click', function() {
var x = $(this).attr('id');
click_delete(x);
});
}
Now, in your success (after you added the new entry):
success(function(data) {
// add your entry...
deleteButton();
});

Words trimmed tooltip jquery

Basically I want my tooltip to display company names once company_id is being hovered. However instead of displaying "Company A" for example, it just displays "Company". I realized that it's just printing everything before a space.
Here's the script:
<script type="text/javascript">
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>')
.text(title)
.appendTo('body')
.fadeIn('slow');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({ top: mousey, left: mousex })
});
});
</script>
and here's my codes
<?php
$companyCtrl = new company_controller();
$companyInfoArr = $companyCtrl->retrieveAllCompanyInfo();
foreach($companyInfoArr as $info) {
$company_id = $info->getCompanyID();
$company_name = $info->getCompanyName();
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
}
?>
There's not problem when i manually enter the text like this
Your Text
In this line:
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
You need to add quotes around the title, so the HTML you're generating will be properly formed. Like this:
echo "".$company_id." <br>";

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