Run JavaScript From Dynamically Created Links - javascript

I am creating a blog style website in which it pulls information from a database to create each post dynamically. Once all the posts have been created the header from each of the posts will open an overlaid div which brings up the whole article for that particular post.
How the posts are created...
<table class="mainTable">
<tr>
<td id="mainBanner">
<img class="startLogo" src="images/logo.png">
</td>
<?php
$sql = 'SELECT * FROM posts ORDER BY Post_ID DESC';
$result = mysqli_query($conn, $sql);
if($result){
while($row = mysqli_fetch_assoc($result)){
?>
<td class="<?php if($row['Post_Featured'] == 0) {echo 'visualPost';} else {echo 'featuredPost';} ?>" id="<?php echo $row['Post_ID']; ?>">
<a id="openOverlay" name="<?php echo $row['Post_ID']; ?>" href="#">
<?php echo $row['Post_Title']; ?>
</a>
<img src="images/<?php echo $row['Post_Image_Embed']; ?>" width="100%">
<p><?php echo $row['Post_Blurb']; ?> Votes:<?php echo $row['Post_Votes']; ?></p>
</td>
<?php
}
}
?>
</tr>
</table>
JavaScript
var createOverlay = document.getElementById("openOverlay");
var destroyOverlay = document.getElementById("closeOverlay");
createOverlay.onclick = toggleOverlay;
destroyOverlay.onclick = toggleOverlay;
function toggleOverlay() {
var postID = $(this).attr('name');
var specialBox = document.getElementById('specialBox');
var container = document.getElementById('container');
if (container.style.display == "block") {
document.body.style.overflowY = "hidden";
container.style.display = "none";
specialBox.style.display = "none";
$("body").mousewheel(function (event, delta) {
this.scrollLeft -= (delta * 20);
event.preventDefault();
});
$('div#postOverlay').empty();
} else {
document.body.style.overflowX = "hidden";
container.style.display = "block";
specialBox.style.display = "block";
$("body").unmousewheel();
$.ajax({
type: "POST",
url: "overlayFill.php",
data: { 'id': postID },
success: function (data) {
$('div#postOverlay').append(data);
}
});
}
event.preventDefault();
}
I tried using document.getElementById('openOverlay') to grab the link and run the JavaScript needed to bring up the overlay depending on the post and running a php script to grab the information from the database and post it to the overlay but it seems like it only grabs the first dynamically created id (aka the first id getElementById hits) the rest of the posts won't bring up an overlay.
Overlay
<div id="container">
<div id="specialBox">
<a id="closeOverlay" href="#">Close</a>
<div id="postOverlay"></div>
</div>
</div>
Is there a better way to do this? I thought about maybe trying a button but I thought I would end up with the same issues.

Change <a id="openOverlay" to <a class="openOverlay" (and the same with #closeOverlay) and use jQuery's .on(), like so:
$(document).ready(function(){
$(document).on('click', '.openOverlay, .closeOverlay', toggleOverlay);
});
This allows the event to be bound to elements that have not been added to the dom yet.

Instead of dynamically creating the block that has another id attribute, you should use class='closeOverlay'.
Then instead of getElementById('closeOverlay') you can use getElementsByClassName('closeOverlay'), and add your function to each of element in that return array.

Related

Add delete button or symbol to delete the retrieved images from database

I have created an image gallery using the PHP code below, which will retrieve the images from a database. Now I want to add a delete symbol to the images so that I can delete it after getting retrieved from the database. Kindly help me out. How can i do this?
<div class="header">
<h2>
GALLERY
<!--<small>All pictures taken from unsplash.com</small>-->
</h2>
<hr/>
<div class="body">
<div id="aniimated-thumbnials" class="list-unstyled row clearfix">
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" />
</a>
<?php }
} ?>
</div>
</div>
</div>
you can add a delete button simply like
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a id="imageid-<?=$row[0]?>" href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" />
<div class="delete" data-imgId="<?=$row[0]?>">Delete</div>
</a>
<?php
}
}
?>
then handle the click of that button and an ajax call like
$(".delete").click(function(e){
var rowId = e.target.dataset.imgId;
$.ajax({
method: 'DELETE',
url: "", // url to delete
data: {image_id: rowId}
success: function(){
$('imageid-'+rowId).hide();
}
});
});
here it will pass the image id as a parameter to the api call, and will hide the image once the api call is success.
if($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" /></a>
<!-- HERE YOU CREATE SPAN AND GIVE IMAGE ID AS DATA ID
<span class="deleteImage" data-id="<?=$row[0]?>">Delete Image</span>
<?php }
And Ajax Call is As follow
$(".deleteImage").click(function(){
$.ajax({
//PAGE THAT DELETE IMAGE
url: "delete_image_page.php",
context: document.body,
data: {data:data}
success: function(){
//ON SUCCESS WHAT YOU WANT TO DO
$(this).addClass("done");
}
});
});
NOTE: For more information read this Documentation.
And you should have to readthis post before asking this type of question.
This is a small example. Basically, on a click of a button you would call an AJAX method to send the image name you want deleted. The request needs to be sent to another PHP file that will receive the request, process it, and return a response. Based on the response we get we will know if the method was successful.
You need an additional Javascript file to hold the AJAX function, and a additional PHP file to handle the request and return a response.
Your PHP file:
<div class="header">
<h2>GALLERY</h2>
<!--<small>All pictures taken from unsplash.com</small>-->
<hr/>
<div class="body">
<div id="aniimated-thumbnials" class="list-unstyled row clearfix">
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0)
{
while($row = $query->fetch_assoc())
{
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
echo '<div class="imageContainer">
<a href="'.$imageURL.'" data-fancybox="group" data-caption="'.$row['title'].'" >
<img src="'.$imageThumbURL.'" alt="" />
</a>
<input type="button" onclick="deleteImage(\''.$row["file_name"].'\')" value="Delete" />
</div>';
}
}
?>
</div>
</div>
</div>
The Javascript file:
// Send the `fileName` of the image
function deleteImage(fileName)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('Success, deleted: ' + fileName + ' Response: ' + this.responseText);
}
else if(this.responseText == "Not OK")
{
alert('Picture: ' + fileName + ' was not deleted.');
}
}
};
// For example you send a request to deleteImage.php sending `fileName` info
// - deleteImage.php just needs to echo the response to answer back
xhttp.open("GET", "deleteImage.php?fileName=" + fileName, true);
xhttp.send();
}
The other PHP file, deleteImage.php (the AJAX request receiver):
<?php
$con = ... // Here goes DB connection data
if(isset($_GET['fileName']) && $_GET['fileName'] != '')
{
// Clean the input
$clean['fileName'] = mysqli_real_escape_string($con, $_GET['fileName']);
// Do something
}
// if successful echo 'OK';
// if not successful echo 'Not OK';
?>

Retrieve image from JSON file which is in the database and display in HTML img tag

I really dont know where the hell i am wrong. May be it is simple but I can't figure it out. Any help would be great, please and thank you.
JSON code (it is stored in 'images' column in tblproducts table in the database)
{"200x200":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-200x200-imaezt6hypjzhdug.jpeg","400x400":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-400x400-imaezt6hypjzhdug.jpeg","800x800":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-800x800-imaezt6hypjzhdug.jpeg","unknown":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-original-imaezt6hypjzhdug.jpeg"}
HTML & PHP Code:
<?php
$category_id = $_GET['category_id'];
$result = mysql_query("select * from tblproducts where category_id = '$category_id");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
?>
<script>
var data =
data.forEach( function(obj) {
var img = new Image();
img.src = obj.Img1;
img.setAttribute("class", "banner-img");
img.setAttribute("alt", "effy");
document.getElementById("img-container").appendChild(img);
});
</script>
<img id="img-container" alt=" " class="img-responsive" />
<h5>
<a target="_blank" href="<?php echo $row['product_url']; ?>">
<?php echo $row['product_title']; ?>
</a>
</h5>
<?php echo $row['maximum_price']; ?>
<?php } ?>
I have no idea about the javascript and how to fetch each of the image from the json and display it in different tag. Please help... Thanks in advance
Assuming your JSON is stored as string in column images. You can do something like this:
// ...
<script>
var data = <?php echo json_decode($row['images']); ?>
Object.keys(data).forEach(function(key) {
var img = new Image();
img.src = data[key];
img.setAttribute("class", "banner-img");
img.setAttribute("alt", "effy");
img.classList.add('img-responsive');
document.getElementById("img-container").appendChild(img);
});
</script>
<div id="img-container"></div>
<h5>
<a target="_blank" href="<?php echo $row['product_url']; ?>">
<?php echo $row['product_title']; ?>
</a>
</h5>
// ...
I've changed the image append logic, what you were doing was wrong. You cannot append images that way, instead create a container and append the newly created images in that container.

PHP search using AJAX with checkbox

How do I let AJAX know what I have checked with checkbox? I have a list of categories that are selected from a database. So how do let the AJAX know what I have checked?
This is my search PHP:
<div class ="search-category-container">
<div class ="search-category-header featured-header">
<label class ="featured-font">category</label>
</div>
<div class ="search-category-content">
<?php
$result=mysqli_query($connection,"SELECT * FROM category");
while($row= mysqli_fetch_array($result)) { ?>
<label class="checkbox category-list ">
<input type="checkbox" name="category_list[]" value="<?php echo $row['name']; ?>" form="search-form"><?php echo $row['name']; ?>
</label>
<?php
}
?>
</div>
</div>
This is my search function using on search before without AJAX. Now I was trying to use AJAX to get data can I use back the function?
<?php
if($filter == "post" && $time == "all" && $status == "all" && isset ($_POST['category_list'])) {
foreach ($_POST['category_list'] as $category) {
$result = mysqli_query($connection, "SELECT * FROM category WHERE name IN ('$category')")or die(mysqli_error($connection));
while($row= mysqli_fetch_array($result)) {
$getCategory = $row['id'];
$getPostIDRow = mysqli_query($connection, "SELECT * FROM post_category WHERE category_id = '$getCategory'") or die(mysqli_error($connection));
while($row2= mysqli_fetch_array($getPostIDRow)) {
$getPostID = $row2['post_id'];
$result2 = mysqli_query($connection,"SELECT * FROM post WHERE title LIKE '%$search%' AND id = '$getPostID'") or die(mysqli_error($connection));
$count2 = mysqli_num_rows($result2);
if($count2>0) {
while($row2= mysqli_fetch_array($result2)) {
$postID = $row2['id'];
$result3 = mysqli_query($connection, "SELECT * FROM user_post WHERE post_id = '$postID'") or die(mysqli_error($connection));
while($row3 = mysqli_fetch_array($result3)) {
$getUserName = mysqli_query($connection, "SELECT * FROM user WHERE id = '".$row3['user_id']."'")or die(mysqli_error($connection));
while($row4 = mysqli_fetch_array($getUserName)) {?>
<div class ="post-container" id="search-container">
<div class ="post-header-container">
<div class ="post-header">
<a href ="post.php?id=<?php echo urlencode($row2['id']);?>&user=<?php echo $row3['user_id']; ?>">
<p class ="post-header-font"><?php echo ($row2['title']); ?></p>
</a>
</div>
<div class ="post-user">
<p class ="faded-font">by : <?php echo $row4['username']; ?></p>
</div>
</div>
<div class ="post-content-container">
<p class ="post-content-font">
<?php echo ($row2['summary']); ?>
</p>
</div>
<div class ="post-info-container">
<div class ="post-info">
<span class ="glyphicon glyphicon-eye-open"> views: <?php echo ($row2['views']);?></span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-pencil"> answers:</span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-ok"> status: <?php echo ($row2['status']);?></span>
</div>
</div>
</div><?php
}
}
}
}
}
}
}
?>
This is AJAX search function
$(document).ready(function(){
function search() {
var searchWord = $("#search").val();
var filter = $("#filter:checked").val();
var time = $("#time:checked").val();
var status = $("#status:checked").val();
$.ajax({
type:"post",
url:"searchFunction.php",
data:"search="+searchWord+"&filter="+filter+"&time="+time+"&status="+status,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
$("#searchButton").click(function(){
search();
});
$("#search").keyup(function(e){
if(e.keyCode == 13) {
search();
}
});
});
To answer you ajax question I highly recommend changing your code to use the 'form' DOM for user experience and easier maintenance, just fyi and use the serialize function which will also send out the 'checked' checkboxes.
https://api.jquery.com/serialize/
function search() {
var postData = $('myForm').serialize(); // i.e <form id="myForm">
$.ajax({
type:"post",
url:"searchFunction.php",
data: postData,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
That will do all the work for you automatically instead of having to run a bunch of jQuery selection calls and putting together the HTTP query your self. If you ever need to know what your ajax is running. Go in inspector mode of your browser and look for "Network" tab, click that and you should see the ajax call to that search file, with everything you need to know. What HTTP request and response headers are and body.
P.s make sure you return false on the submit event and that the name of the fields on your HTML form match the $_POST key names for the ajax.
$("#myForm").on('submit', function(){
search();
return false;
});
Good luck!

Pulsate not executed after click with PHP

I have a pulsate:
<script>
$(document).ready(function() {
$(".pane > a").click(function (event) {
event.preventDefault();
$(this).parent().effect("pulsate", { times:2 }).fadeOut('slow');
});
});
</script>
Then the PHP:
<?php
if($_SESSION['username']) {
if(isset ($_GET['id'])) {
mysql_query("DELETE FROM reviews WHERE id='". mysql_real_escape_string($_GET['id']) ."'");
}
}
$grab = mysql_query("SELECT * FROM reviews");
if (mysql_num_rows($grab)==0) {
echo ("<div class=''><strong>Sorry!</strong> No reviews have been created!</div>");
}
while($row = mysql_fetch_array($grab)){
?>
<div class="pane">
<img src="http://uploadir.com/u/6hmr4fr1" alt="delete" class="delete" />
<?php echo $row['comment'] ?>
</div>
It works but doesn't delete from the database. I'm working on an AJAX script, which works perfect, but it's something I'm not doing right here.
It pulsates out with:
<a href="reviews/editReview/<?php echo $row['id'] ?>"rel="noAJAX">
but when I take out the rel="noAJAX" it deletes the information from the database, which I want to happen, but it isn't pulsating then deleting.
Any ideas? I'm using jQuery UI 1.8.2 & jQuery 1.5

my little bit of ajax over an element in a table breaks if table is large. how to fix?

I have page with multiple tables being generated by php/mysql. One of the elements is a in/out button. I have it ajax'ed so that the button changes to the on or off image with each click without reloading the page.
And it worked like charm! Until it didn't. If one table or a combination of tables exceeds so many rows...it stops working. But still works on the rows above it. Why would that be?
Here's the table generation...this occurs in multiple php files.
<tbody>
<?php while($row = MySQL_fetch_array($result)):
$id = htmlentities($row['id']);
$status = htmlentities($row['status']);
include ("button.php");
?>
<tr>
<td title="lname" width="100px">
<div style="width:100px; overflow:hidden;">
<?php echo(htmlentities($row['last_name'])); ?>
</div>
</td>
<td width="100px">
<div style="width:100px; overflow:hidden;">
<?php echo(htmlentities($row['first_name'])); ?>
</div>
</td>
.
.
.
<td>
<div style="width:100px; overflow:hidden;">
<?php echo '<div><div id="r'.$id.'"><div id="test"><img class="rating" id="'.$status.$id.'" src="'.$color.'"><div style="display:none;">'.$status.'</div></div></div></div>';?>
</div>
</td>
</tr>
<?php endwhile; ?>
Here's the script:
<script>
$(function(){
$(document).on("click", ".rating", function(){
var status = $(this).attr("id").substr(0,1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&status="+status;
$.ajax({
type: "POST",
url: "rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
</script>
Here's the rate.php referenced in the code above:
<?php
include ("db.php");
$id = $_POST["id"];
$newstatus = $_POST["status"];
if($newstatus == 0){
mysql_query("UPDATE users SET status = 1 WHERE id='$id'");
}
else {
mysql_query("UPDATE users SET status = 0 WHERE id='$id'");
}
include("button.php"); //FILE WITH THE LIKE & DISLIKE BUTTONS AND THE NUMBER OF LIKES & DISLIKES
$list = '<div id="test"><img class="rating" id="'.$q[0].$id.'" src="'.$color.'"><div style="display:none;">'.$q[0].'</div>';
echo $list;
?>
And the button.php file referenced above:
<?php
$q = mysql_query("SELECT status FROM users WHERE id='$id'");
$q = mysql_fetch_array($q);
if($q[0]){
$color = "green.png";
}
else{
$color = "red.png";
}
?>
So yeah...if the mysql query for one table is too large, after a certain number of rows, the in/out buttons stop working. Or if I have multiple smaller tables, once it exceeds a certain total number of rows, same thing.
Help?
While debugging in comments, it was realized that duplicate id's were being used. ID's must be unique within a single page, otherwise unexpected results may occur (such as the problem described in the question).
To test for duplicate id's, use the attribute equals selector.
console.log($("[id=" + theidtotest + "]").length)
if you ever get more than 1 elements from that line, you're doing something wrong.

Categories