I'm trying to make Jquery delete function, here is the code, that I wrote -
$("a.delete").click(function(){
var target = $(this).attr("id");
var c = confirm('Do you really want to delete this category?');
if(c==true) {
$(target+"ul").delay(3000).fadeOut(200);
}
else {
return false;
}
});
Okay now to problem, when I press, button a with class delete, it correctly, shows up the dialog (and the id is correct), but after I press yes, it will delete it with php, without jquery fadeOut effect.
My php code -
public function deleteCategory() {
if(isset($_GET['action']) && $_GET['action'] == 'delete') {
$id = (int)$_GET['id'];
$sql = "DELETE FROM `categories` WHERE `id` = '".$id."'";
mysql_query($sql);
}
}
Not sure where is the problem but I think it's inside $(target+"ul"), since I'm not sure, if it will add the target value and ul together.
In additional, how can I prevent the delete, if I press no? Currently, if I press no, it will still delete the category.
If you need any other information - ask.
Full code -
public function showCategories() {
if(isset($_SESSION['logged_in']) && isset($_SESSION['user_level']) && $_SESSION['user_level'] == 'admin') {
$sql = "SELECT * FROM `categories`";
$q = mysql_query($sql);
if(mysql_num_rows($q) > 0) {
?>
<div class="recentorders" style="display: none;" id="categoryBox">
<h5 class="colr">Categories</h5>
<div class="account_table" style="width: 688px;">
<ul class="headtable" style="width: 680px;">
<li class="order">ID</li>
<li class="action" style="width: 430px;">Category Name</li>
<li class="action nobordr">Options</li>
</ul>
<?php
while($row = mysql_fetch_array($q)) {
?>
<ul class="contable" style="width: 680px;" id="cat<?php echo $row['id']; ?>ul">
<li class="order"><?php echo $row['id']; ?></li>
<li class="action" style="width: 430px;"><?php echo $row['name']; ?></li>
<li class="action nobordr">Edit<a class="delete" id="cat<?php echo $row['id']; ?>" href="?action=delete&id=<?php echo $row['id']; ?>#">Delete</a></li>
</ul>
<?php
}
?>
</div>
</div>
<?php
}
else {
// No categories created, please create one first.
}
}
else {
header('location: account.php');
}
}
public function deleteCategory() {
if(isset($_GET['action']) && $_GET['action'] == 'delete') {
$id = (int)$_GET['id'];
$sql = "DELETE FROM `categories` WHERE `id` = '".$id."'";
mysql_query($sql);
}
}
If you're searching by ID you need to prefix your selector with a "#":
100% working sample on jsFiddle:
http://jsfiddle.net/E7QfY/
Change
$(target+"ul").delay(3000).fadeOut(200);
to
$('#' + target+"ul").delay(3000).fadeOut(200);
OR
$(this).closest('ul').delay(3000).fadeOut(200);
I would also modify the code to this:
$("a.delete").click(function(event){
if(confirm('Do you really want to delete this category?') == true){
$(this).closest('ul').delay(3000).fadeOut(200);
window.location.href = $(this).attr('href'); //OR use AJAX and do an event.preventDefault();
}
else
event.preventDefault();
});
It's because you are using an anchor tag that is causing a postback to the server which makes your page refresh before you see the animation. Make sure your anchor tag has an href defined as "#" to stop the postback from happening.
You should use something else than A tag e.g. span or div. And then after clicking this element make your fadeout and after it redirect to the PHP script that deletes your object:
$("SPAN,DIV.delete").click(function(){
var target = $(this).attr("id");
var c = confirm('Do you really want to delete this category?');
if(c==true) {
$(target+"ul").delay(3000).fadeOut(200);
window.location.href = URL TO PHP FILE
}
else {
return false;
}
});
Related
On my main page I have a content box where I load the content using Jquery's load() from another page. All is working fine and it's quick and nice.
Next thing I want to do is to add a small filtering feature to it. The variable is sent to the main page (snappage.php) as a GET variable. However the php for the sql query is in another page (i.e all-snaps.php). Let me show you my code:
snappage.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
}
?>
<section class="main-snap-page-wrapper">
<nav class="all-snaps-countries">
<h4>Filter by country</h4>
<ul>
<?php
//GET COUNTRY FLAGS
$flagsql = mysql_query("SELECT * FROM countries");
while($getflag = mysql_fetch_array($flagsql)) {
$countryname = $getflag['countryname'];
$flag = $getflag['countryflag']; ?>
<li>
<a href="snappage.php?country=<?php echo $countryname?>">
<img src="<?php echo $flag?>" alt="">
<h5><?php echo $countryname?></h5>
</a>
</li>
<?php } ?>
</ul>
</nav>
<div class="all-snaps-page">
<nav class="main-page-tabs-wrapper">
<ul class="main-page-tabs" id="<?php echo $country?>">
<li class="active-tab">All</li>
<li>Female</li>
<li>Male</li>
</ul>
<div class="main-snaps-content"></div>
</nav>
</div>
</section>
<script type="text/javascript">
$('.main-snaps-content').load('all-snaps.php');
$('.main-page-tabs li').on('click', function () {
$('.main-page-tabs li').removeClass('active-tab');
$(this).addClass('active-tab');
var page = $(this).find('a').attr('href');
$('.main-snaps-content').load(page + '.php');
return false;
});
</script>
Next is the page which I load into .main-snaps-content from i.e all-snaps.php:
all-snaps.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
$newsql = mysql_query("SELECT * FROM users JOIN fashionsnaps ON users.id = fashionsnaps.userid WHERE country = '$country' ORDER BY snapid ASC");
}
else {
$newsql = mysql_query("SELECT * FROM fashionsnaps ORDER BY snapid ASC");
}
?>
<ul class="snaps-display">
<?php
//GET SNAPS BY ID
while ($getnew = mysql_fetch_array($newsql)) {
$newsnappics = $getnew['snappic'];
$newsnapid = $getnew['snapid'];
?>
<li>
<a href="snap.php?id=<?php echo $newsnapid?>">
<img src="<?php echo $newsnappics?>" alt="">
</a>
</li>
<?php } ?>
</ul>
So what I want to achieve here is to load the filtered content from all-snaps.php into the .main-snaps-content which is on snappage.php.
Where should I send this $country variable? On which page should I retrieve it?
You can do this pretty easily with jQuery load.
In snappage.php:
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: "<?php echo htmlentities($country); ?>"}));
Update:
You'll need better handling of the PHP GET/$country var. You can initialize it at the top of snappage.php like this:
$country = (isset($_GET['country'])) ? $_GET['country'] : '';
Then, your JS will need a conditional:
var country = "<?php echo htmlentities($country); ?>";
if (country) {
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: country}));
} else {
$(".main-snaps-content").load("all-snaps.php");
}
I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.
update :
The problem now is after using firebug I found out that the first element gets the title attribute and other elements don't and after hovering on any link the title attribute of the first link disappears any ideas?
I have a which page opens when I click on a link like this:
<a class="pictures" href="#" onClick="MM_openBrWindow('content_image.php','images','menubar=yes,scrollbars=yes,resizable=yes,width=650,height=700')" title="Images"></a>
This page has images stored in a folder:
$open = opendir($path);
while($images = readdir($open)){
if ($images != "." && $images != "..") {
$allimages[] = $images;
}
}
foreach($allimages as $val){
?>
<div class="uploaded_image"><img src="../content_img/<?php echo $val; ?>" align='middle' width='150px' height='100px'>
<form><img src="images/delete.gif"/> <textarea name='text_area' rows=1 cols=20 >../content_img/<?php echo $val; ?></textarea> <input type='button' value='select path' onClick='javascript:this.form.text_area.focus();this.form.text_area.select();'> Copy path and paste in image path field </form></div>
<?php
}
closedir($open);
?>
I am trying to delete images using a regular link with href to the page with the following attributes:
?do=delete&img=<?php echo $val; ?>
and then unlink() the image. However, the image is deleted as soon as I hover on the link without clicking. I don't know why.
I tried to do it using AJAX:
$(document).ready(function(e) {
$("div.uploaded_image").on("click","a.del_img",function(e){
e.preventDefault();
var img = $(this).attr("title");
var qst = "?img="+img+"&path=content_img";
var ajax = false;
ajax = new XMLHttpRequest();
ajax.open("post","del_image.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
}
}
ajax.send(null);
setTimeout(ref,1500);
});
});
function ref(){
window.location = "content_image.php"
}
and this PHP code work uses AJAX to delete:
$img = $_REQUEST['img'];
$path = $_REQUEST['path'];
unlink("../".$path."/".$img);
When I click on the delete link for the first time it doesn't work. I have to click again to delete the image. Any help please?
$open = opendir($path);
while($images = readdir($open)){
if ($images != "." && $images != "..") {
$allimages[] = $images;
}
}
foreach($allimages as $val){
?>
<div class="uploaded_image"><img src="../content_img/<?php echo $val; ?>" align='middle' width='150px' height='100px'>
<form><img src="images/delete.gif"/> <textarea name='text_area' rows=1 cols=20 >../content_img/<?php echo $val; ?></textarea> <input type='button' value='select path' onClick='javascript:this.form.text_area.focus();this.form.text_area.select();'> Copy path and paste in image path field </form></div>
<?php
}
closedir($open);
?>
replace code with this code
change
$("div.uploaded_image").on("click","a.del_img",function(e){
e.preventDefault();
to
$("div.uploaded_image a").click(function(e){
e.preventDefault();
...
I have been struggled with one sticky issue regarding to set default li.
what I try to achieve is that set a li and its related page as default one. And when users click on others links, it would load other pages.
HTML Markup:
<div id="productIntro">
<div id="leftNav">
<ul>
<li class="head">
Pictures</b>
</li>
<li class="head">
<b>Comments</b>
</li>
<li class="head">
<b>Others</b>
</li>
</ul>
</div>
<div class="main">
</div>
</div>
JS:
function show(id, page) {
$('.main').load("loadProDetail.php?id=" + id + "&page=" + page, true);
}
jQuery(document).ready(function () {
$(document).on('click', '.head', function () {
$(".head").removeClass("selected");
$(this).toggleClass("selected");
});
});
loadProDetail PHP
<?php
$id = $_GET['id'];
$sql = "select * from product where id=$id ";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$page = $_GET['page'];
if($page == 1)
{
$html .= '<img src="./product_images/' . $row["name"] . '.jpg" width="150" border="2">';
}
if($page == 2)
{
$html .= 'No comments so far';
}
if($page == 3)
{
$html .= 'This page is under construction';
}
echo $html;
CSS:
.selected{background-color:red;}
In my case, I want to set the "Picutre" li as default page, and when user click on comments, it would load corresponding page. And also the background colour should also be changed.
Your page logic lives in your PHP, so specifying which page should display by default can be added there by modifying your if statements and making them into if...else instead:
if ($page==2) {
$html .= 'No comments so far';
} else if ($page==3) {
$html .= 'This page is under construction';
} else {
$html .= '<img src="./product_images/'.$row["name"].'.jpg" width="150" border="2">';
}
The logic implemented above goes like this: if the "Comments" or "Others" pages are requested, serve them, but if not then just serve the "Pictures" page.
Since you also want to load the "Picture" content when the page is initially loaded, you can call the show() function in your Javascript on pageload. Adding the following line to your existing jQuery(document).ready(function () { ... } should work as long as $row["id"] is properly set:
show($row["id"], 1);
In 1stpage I have a table with full of data, and end of every row there is a delete link. When i click on that link, the link goes to another delete page where mysql delete query delete that particular data from database. That delete page redirect with the 1st page (location:1stpage). Now when i want to apply a javascript delete yes/no checking, every time it pops up with "Are you sure?" either i press yes or no the data is deleted from my table. I think the return false cannot working in this case. The code are in below. Please help me what should i do exactly.
Sorry for my bad english.
Thanks in advance.
1st page:
<?php
include "include.php";
?>
<script type="text/javascript">
function show_confirm()
{
var con = confirm("Are You Sure");
if (con ==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
<table>
<tr>
<td align="center">EDIT OR DELETE DATA</td>
</tr>
<tr>
<td>
<table border="1">
?php
if(isset($_POST['submit']))
{
$order = "UPDATE books SET author='$_POST[author]', title='$_POST[title]', price='$_POST[price]' WHERE isbn='$_POST[isbn]'";
mysql_query($order) or die (mysql_error());
}
$order = "SELECT * FROM books ORDER BY author" or die (mysql_error());
$result = mysql_query($order);
while ($row=mysql_fetch_array($result))
{
echo ("<tr>
<td>$row[isbn]</td>
<td>$row[author]</td>
<td>$row[title]</td>
<td>$row[price]</td>
<td> Edit </td>
<td> <a href=\"delete.php?isbn=$row[isbn]\" onclick='show_confirm()'> Delete </a> </td>
</tr>");
}
?>
</table>
</td>
</tr>
</table>
the page where mysql delete query run :
<?php header("Location: editordeletedata.php"); ?>
<p> <title>delete</title> </p>
<?php
include "include.php";
?>
<?php
if(isset($_GET['isbn']))
{
$order = "DELETE FROM books WHERE isbn = '$_GET[isbn]'";
mysql_query($order) or die (mysql_error());
}
?>
Look at this simple code snippet I wrote, should get you fixed up right.
<html>
<head>
<script type="text/javascript">
function show_confirm() {
return confirm("Are You Sure");
}
</script>
</head>
<body>
<a href="http://www.google.com" onclick='return show_confirm();'> Google </a>
</body>
</html>
Fiddle
I don't see any reason why return false will not work.
function show_confirm()
{
if (confirm("Are You Sure"))
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
return false;
}
}
Disable the delete link and move the redirection to the javascript function. The link should look like this:
<a href=\"javascript:void(0)\" onclick='show_confirm($row[isbn])'> Delete </a>
And the javascript function just like this:
function show_confirm(isbn)
{
if (confirm("Are You Sure"))
{
alert("You pressed OK!");
location.replace('delete.php?isbn='+isbn);
}
else
{
alert("You pressed Cancel!");
}
}