I have a code that works fine except one thing. When you click onto the Delete button, a modal box appers and it shows 2 buttons. When you click onto the OK button it should delete that user's data which you clicked. But this is deletes the user who has the lowest ID. But if I removes the modal box opening function and simpy just put a href='delete.php?id=".$roww['id']."' it works fine. Any idea how to solve this?
Code from the index.php:
include "dbConn.php"; // Using database connection file here
$records = mysqli_query($db,"select * from accounts"); // fetch data from database
while($data = mysqli_fetch_array($records)) {}
$conn = mysqli_connect("localhost", "root", "", "phplogin");
if ($conn-> connect_error) {
die("Connection failed:". $conn-> connect_error);
}
$ssql = "SELECT * FROM accounts";
$result = $conn-> query($ssql);
if ($result-> num_rows > 0) {
while ($roww = $result-> fetch_assoc()) {
$id = $roww['id'];
echo "
<span>".$roww['username']."</span>
<span>".$roww['email']."</span>
<a onclick='pop()'>Delete</a>
// Delete modal
<div id='box'>
<img src='/assets/images/svg/rf-alert.svg' width='64px'>
<h1>Attention!</h1>
<p>You are going to delete this user permanently.</p>
<a class='close' href='delete.php?id=".$roww['id']."' title='".$roww['id']."'>Delete</a> // This button should delete the data from the MySQL table
<a class='close' onclick='pop()'>Cancel</a>
</div>
";
} else { echo "0 result";}
}
$conn-> close();
<div id='box'>
All modals will have the same ID, may it be related to opening the first modal always? Try with something like:
<div id='box".$roww['id']."'>
Also you'll have to edit the pop() function to something like pop(id);
A better option would be create the modal dinamically.
Related
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;?>");
});
I know that this question has been asked before,I have read the answer,implemented it,but I am facing one small problem.
In the PHP file I am trying to make an anchor tag and then display it in the popover,but instead making it clickable,the whole content(along with the anchor tag) is displayed.
Also,once the icon is clicked,it sticks around and doesn't go away even after clicking on it or anywhere else on the page.
Here is the code:
HTML file:
<li style="margin-left: 15px;">
<a href="#" data-placement="bottom" title="notifications" data-poload="notification_list.php" id="id-wala">
<img src="assets/ring.png" width="25" height="25" data-toggle="tooltip" data-placement="bottom" title="notifications">
</a>
</li>
AJAX code
$('*[data-poload]').click(function() {
console.log('Hey');
var e=$(this);
e.off('click');
e.unbind('click')
$.get(e.data('poload'),function(d) {
console.log(d);
e.popover({content: d}).popover('show');
});
});
PHP file
<?php
#The code for connecting to the database removed for clarity.
$sql1 = "SELECT PID from post where UID = '$a'";
$result1 = mysqli_query($conn,$sql1);
$end_result = '';
while($row1 = mysqli_fetch_assoc($result1)) {
$temp = $row1["PID"];
$sql = "SELECT * from comment where status = 'unread' and PID = '$temp' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$end_result='<a href ="#" >'.'Notification from '.$row["UID"].'</a>';
echo $end_result;
echo '<br/>';
}
}
}
$conn->close();
?>
The problem is that the echo $end_result is printing <a href ="#" >Notification from 89</a> instead of Notification from 89 and making it clickable.
Please provide some suggestions on how to fix this problem.
The issue is because by default the html property on the popover is false. This means any HTML you attempt to place inside the popover content will be removed. To change this behaviour you need to set html: true.
You'll also need to use trigger: 'manual' and use the toggle option to hide/show the popover on successive clicks. Try this:
e.popover({
html: true,
trigger: 'manual',
content: d
}).popover('toggle');
Working example
Bootstrap Popover documentation
I used the network developer tool to see if the id is sent to the other page. Which it successfully did. And I can see the other page echo the result but it doesn't show in the modal in the other page even though I have the results.php included in the modal div. Anybody know why this is happening?
itempage.php code:
<div id="globalmodal" class="modal">
<div class="modal-content">
<?php include ("getdata.php");?>
</div>
</div>
results.php code:
if (!empty($_POST["data"])) {
$server = '';
$dbname = '';
$dsn = "mysql:host=".$server.";dbname=".$dbname;
$username = '';
$password = '';
$newdata = $_POST["data"];
$db = new PDO($dsn, $username, $password);
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id LIKE '%$newdata%' GROUP BY `id`");
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
if($row['id']) {
$pTitle = $row['title'];
echo '<h4>'.$pTitle.'</h4>';
echo "Yes it was received!";
}
}
In the itempage.php the getdata.php is included in the div for the modal. But the modal doesn't show the results in the getdata.php page even though the getdata.php has the right title from the database. But the echo doesn't show in the modal pop up.
There is a small typographical error in the SQL query:
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id LIKE '%$newdata%' GROUP BY `id`");
It has a missing ``` (it is opened but not closed) for the id used in the like. That causes a SQL error, and the condition that displays the result will never be executed (as $row['id'] will not exist).
As a quick solution, just close it properly like this:
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id` LIKE '%$newdata%' GROUP BY `id`");
So I fixed it, I had to leave url for $.ajax blank.
I've been working on a 9gag like page. I tried to integrate a voting system which has been made by another guy, because I'm not really familiar with AJAX requests, and it just doesn't want to work.
My index.php loads five posts from the mySQL database then it appends them to the main div. After you scroll down it appends five more etc. This is done by an AJAX request which works like a charm.
When I append it to the div by AJAX, I also append some variables in the div so I can then use it for another AJAX request and this is where the problem occurs. It just doesn't do any AJAX requests. After an hour of debugging I've come to question whether one can append some data to a div, which doesn't exist in the original index.php and then run AJAX requests with it.
I won't post the pagination.js and it's stuff here because it works, I'm only going to post the ajax.php request where it could go wrong:
<?php
include 'config/connection.php';
$db = "test";
$table = "posts";
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$run = mysqli_query($con,"SELECT * FROM $db.$table ORDER BY id DESC LIMIT ".$postnumbers." OFFSET ".$offset);
while($row = mysqli_fetch_array($run)) {
echo " <article>\n";
echo " <div id='title'><h1>".utf8_encode($row['title'])."</h1></div>\n";
echo " <div id='image'><img src='posts/".$row['dDate']."/".$row['image']."'></div>\n";
echo " <div id='text' class='item' data-postid='".$row['id']."' data-score='".$row['vote']."'>\n";
echo " <p>Beküldte: ".$row['postedBy']."\n";
echo " <div class='vote-span'><!-- voting-->\n";
echo " <div class='vote' data-action='up' title='Vote up'>\n";
echo " <i class='icon-chevron-up'></i>\n";
echo " </div><!--vote up-->\n";
echo " <div class='vote-score'>".$row['vote']."</div>\n";
echo " <div class='vote' data-action='down' title='Vote down'>\n";
echo " <i class='icon-chevron-down'></i>\n";
echo " </div><!--vote down-->\n";
echo " </div>\n";
echo " </div>\n";
echo " </article>\n";
}
?>
The output looks like this:
<article>
<div id='title'><h1>Azért azt mondtam már hogy héjhó halihó, de igazából yolo, mert nem is igaz az, hogy ez tök gáz lenne.</h1></div>
<div id='image'><img src='posts/2014-08-23/Screen Shot 2014-06-29 at 1.00.45 PM.png'></div>
<div id='text' class='item' data-postid='52' data-score='0'>
<p>Beküldte: zsombor
<div class='vote-span'><!-- voting-->
<div class='vote' data-action='up' title='Vote up'>
<i class='icon-chevron-up'></i>
</div><!--vote up-->
<div class='vote-score'>0</div>
<div class='vote' data-action='down' title='Vote down'>
<i class='icon-chevron-down'></i>
</div><!--vote down-->
</div>
</div>
</article>
But, when I inspect the resource it's not in index.php (of course) but only in an ajax.php file, which is appended to the index.php.
Here is the votingsys.js file:
$(document).ready(function(){
// ajax setup
$.ajaxSetup({
url: '../vote.php',
type: 'POST',
cache: 'false'
});
// any voting button (up/down) clicked event
$('.vote').click(function(){
var self = $(this); // cache $this
var action = self.data('action'); // grab action data up/down
var parent = self.parent().parent(); // grab grand parent .item
var postid = parent.data('postid'); // grab post id from data-postid
var score = parent.data('score'); // grab score form data-score
// only works where is no disabled class
if (!parent.hasClass('.disabled')) {
// vote up action
if (action == 'up') {
// increase vote score and color to orange
parent.find('.vote-score').html(++score).css({'color':'orange'});
// change vote up button color to orange
self.css({'color':'orange'});
// send ajax request with post id & action
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
// voting down action
else if (action == 'down'){
// decrease vote score and color to red
parent.find('.vote-score').html(--score).css({'color':'red'});
// change vote up button color to red
self.css({'color':'red'});
// send ajax request
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
// add disabled class with .item
parent.addClass('.disabled');
};
});
});
aaaand the vote.php file:
include('config/connection.php');
# start new session
session_start();
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
$postId = (int) mysql_real_escape_string($_POST['postid']);
# check if already voted, if found voted then return
if (isset($_SESSION['vote'][$postId])) return;
# connect mysql db
dbConnect();
# query into db table to know current voting score
$query = mysql_query("
SELECT vote
from posts
WHERE id = '{$postId}'
LIMIT 1" );
# increase or dicrease voting score
if ($data = mysql_fetch_array($query)) {
if ($_POST['action'] === 'up'){
$vote = ++$data['vote'];
} else {
$vote = --$data['vote'];
}
# update new voting score
mysql_query("
UPDATE posts
SET vote = '{$vote}'
WHERE id = '{$postId}' ");
# set session with post id as true
$_SESSION['vote'][$postId] = true;
# close db connection
dbConnect(false);
}
}
}
?>
So is it possible to use another AJAX request like this or am I doing something really wrong?
I'm using jQuery 1.4.3.
Aha, I bet I know what the problem is. You have five initial divs, which have click event handlers attached to them via this:
$('.vote').click(function(){ ... });
However, you are adding new divs via an infinite scroll device, and these do not have events attached to them. That is correct behaviour, since you are not re-running the code to attach them again.
There is a clever device in jQuery that will help you get around this. It lets you attach events to things now and in the future. To use it, try this:
$('container-selector').on('click', '.vote', function() { ... });
The on method with a 'click' parameter is just the new preferred way of attaching events in jQuery, and if you add your handler as a second parameter it will just do the same as now. However if you add the new parameter, '.vote', it will attach the event to anything matching this inside the overall container selector, even if it did not exist at the time of attaching the event.
You can use 'body' for the container selector here, but for performance reasons it is a good idea to be more specific than that. Just use whatever CSS selector will contain all of the divs to which you wish to attach this particular event handler.
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.