I'v built a application using codeigniter and I have a message system that displays the users messages, this is done with a foreach statement. I have some JS in the background that once a user clicks on 'delete' of a specific message that message hides from view while the JS posts the message ID to my controller and marks that message as deleted. What is happening though is that once a user clicks on delete only the first message hides (only the first foreach value) but all other messages have separate ids but are not responding to the delete click. I should also note that if I click on 'delete' of any message the first message hides and not the message I clicked on.
heres some code:
View
<?php foreach ($rows as $r) : ?>
<li id="notification_<?php echo $r['MID']; ?>"><?php echo anchor("$r[MID]", 'X', array('class'=>'delete', 'rel'=>"$r[MID]")); ?>
<p>
<?php echo anchor("headless/view_msg/$r[MID]", $r['head'], array('rel'=>'notifications')); ?>
<?php if(strlen($r['body'] >= 74)) : ?>
<?php echo $r['body']; ?>
<?php else : ?>
<?php echo substr($r['body'], 0, 74) . "..."; ?>
<?php endif; ?>
</p>
</li>
<?php endforeach; ?>
JS:
$("a.delete").click(function(eve) {
eve.preventDefault();
var MID = $("a.delete").attr('rel');
$.post('headless/notification_read', {
MID: MID},
function(html){
if(parseFloat(html)){
$('#notification_' + MID).hide('slow')
console.log('success');
}else{
console.log('fail');
}
})
});
Im not to sure whats going on here but my guess would be that the javascript is only linking the first foreach and not the rest(if so how would i fix this)
Any help would be appreciated.
Thanks.
$("a.delete").click(function(eve) {
eve.preventDefault();
var MID = this.rel; // `this` would be the element being clicked on....
//var MID = $("a.delete").attr('rel'); this line is the problem....
$.post('headless/notification_read', {
MID: MID},
function(html){
if(parseFloat(html)){
$('#notification_' + MID).hide('slow')
console.log('success');
}else{
console.log('fail');
}
})
});
demo with comments
it seems you have a collection of anchor links that share the "delete" class, so I think this piece of code would always delete the very first one. You may want to specify the specific index of the anchor, something like
$("a.delete")[x].attr('rel')
where x is the index in this collection.
God I already forget how to program in jQuery after half a year! Sorry no other details could be given.
Edit:
Maybe a better way is to retrieve the unique id user is clicking on and pass its rel to your code.
Related
This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});
I've spent the last couple of days wrestling with a .hover script that posts data to a php script then retrieves related data from a database.
Posting id data to the details.inc.php page is working fine. An alert in the script retrieves and show's the data correctly.
The problem arises when i try to include the data in a div, nothing seems to happen. Firefox show's the script to be executing and retrieving the correct id info as it should.
I don't know where from here. I've tried all i can, but my understanding of java is limited
Thanks for any help in advance.
A mouse over function executes and retrieves the id from an image
<img src="#" class="latest" id="id_retrieved_from_DB">
id is then passed through jquery and ajax which retrieves data linked to id from details.inc.php, the data retrieved should then be included in the "details" div
<script type="text/javascript">
//Mouse over
$(function(){
$('.latest').hover(function() {
id = $(this).attr('id');
$.ajax({
cache: false,
url: "details.inc.php",
data: 'hovered_id='+id,
success:function(data){
alert(data);//showing data correctly
//not working here
$("#details").load('details.inc.php', data);
}
});
return false;
}
});
</script>
details.inc.php
<?php require_once('../../Connections/userauthentication_conn.php'); ?>
<?php
require_once('../../includes/session_remap.inc');
require_once('../../includes/tNG_functions.inc.php');
?>
<?php
$KTColParam1_rsDetails = "0";
if (isset($_GET["hovered_id"])) {
$KTColParam1_rsDetails = (get_magic_quotes_gpc()) ? $_GET["hovered_id"] : addslashes($_GET["hovered_id"]);
}
mysql_select_db($database_userauthentication_conn, $userauthentication_conn);
$query_rsDetails = sprintf("SELECT tbl_entries.id_ent, tbl_entries.country_ent, tbl_entries.date_ent, tbl_entries.title_ent, tbl_entries.subject_ent, tbl_entries.description_ent, tbl_entries.image_ent, tbl_entries.url_ent FROM tbl_entries WHERE (tbl_entries.id_ent=%s) ORDER BY tbl_entries.date_ent DESC ", $KTColParam1_rsDetails);
$rsDetails = mysql_query($query_rsDetails, $userauthentication_conn) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = mysql_num_rows($rsDetails);
?>
<!-- Details -->
<a href="<?php echo $row_rsDetails['url_ent']; ?>" title="Go to <?php echo $row_rsDetails['title_ent']; ?>">
<?php
//show if file exists
if (file_exists("../../images/entries/" . $row_rsDetails['id_ent'] . "__img.jpg")) {
?>
<img src="../../images/entries/<?php echo $row_rsDetails['id_ent']; ?>__img.jpg" width="70" height="70">
<?php
}
//end show if file exists
?>
<p class="seriesName"><?php echo $row_rsDetails['subject_ent']; ?></p>
<h4 class="programTitle"><?php echo $row_rsDetails['title_ent']; ?></h4>
</a>
<!-- End -->
<?php
mysql_free_result($rsDetails);
?>
Why are you doing a second ajax call?
If you already have the data available in javascript, you can replace:
$("#details").load('details.inc.php', data);
with:
$("#details").html(data);
if $("#details") is in the script page and that's the div you wish to display the result, you could use only load:
//Mouse over
var id = $(this).attr('id');
$("#details").load('details.inc.php', 'hovered_id='+id, function(data){alert(data);});
Or you could use $.get()
Jquery manual
The POST method is used if data is provided as an object; otherwise, GET is assumed.
And your PHP script uses get.
Here is what i want: I have multiple <h3> tags that are being uses as a link to reveal answers to FAQ's. Also I have added a form in case that the user did not see any question of interest on that page. The link for the form is at the bottom of the page. Now when the user click on the show form link I would like the window to scroll down to the bottom. I have done this, however when I click on any of the link the window also scrolls to the bottom. I want when the user clicks only on the show form link that the window scrolls.
here is what I have so far:
<body>
<?php
$array = array("link 1","link 2","link 3");
foreach($array as $link)
{
echo "<h3 class='link'>".$link."</h3>";
echo "<div>";
//information to be displayed
echo "</div>";
}
?>
<h3 class="forms">Show Form</h3>
//form information here
</body>
here is the javscript:
<script>
$(document).ready(function(){
$('h3').click('bind',function() {
$(this).toggleClass('open').next().slideToggle(500,function(){
var i = $(this).prop('class');
if(i == 'forms')
{
$("html, body").animate({scrollTop: $(document).height()}, "slow");
}
});
});
});
</script>
I have added an alert to verify my output and when I click on <h3 class="forms"> the alert is blank but when I click on the others the alert showed "link". Can someone help me figure out why the alert is showing blank when I click on the <h3 class="forms"> tag?
You are echoing your LI with the link class, instead of $link.
Also, use
if ($(this).hasClass("forms"))
.prop() should really only be used when accessing the DOM element's properties and not attributes (like class or style, width, etc.). If you want the class, use .attr('class') instead (or, as others have mentioned, you can use .hasClass() to test (with jQuery) if an element has a specific class aplied).
to follow-up on .prop vs .class:
Foo Bar link
var a = document.getElementById('foolink'),
$a = $(a);
$a.prop('href') // like directly calling a.href
$a.prop('id') // again, like directly calling a.id
$a.attr('class') // where as it's actually a.className
I've got this lines of code that, when the user clicks on the link, the page should scroll down to the respective anchor.
Turns out that it only works with the first link. The others just fire this exception
Uncaught TypeError: Cannot read property 'slice' of undefined
Here's the code
jQuery
$(document).on('click','#scrollTo',function(){
var to = $(this).attr('class');
//alert(to);
//This allways print the correct class name
$(window).scrollTo('div #'+to,'1000');
});
PHP
<ul id="source">
<?php
$sourceRCS = $source->getAllSources();
foreach($sourceRCS as $src)
{
echo '<li data-value="'.$src->name.'">'.$src->name.'</li></a>';
}
?>
</ul>
foreach($sourceRCS as $src)
{
echo '
<div class="custom-label-src">
<div id="'.$src->name.'" class="span12 label-title-src">
'.$src->name.'
</div>
</div>';
}
What am I doing wrong?
Thank you in advance
ID's are supposed to be unique, but you repeat #scrollTo. Try using a CSS class as your target instead.
var to = $(this).attr('class');
$(window).scrollTo('div #'+to,'1000');
You are selecting a class and assigning it to "to". Then you take the class and convert it into an ID in the next line.
Your selector should be like this:
var to = $(this).attr('class');
$(window).scrollTo('div .' + to,'1000');
Html Id's have to be unique. Like previously suggested, try using classes instead. Also, try capturing the event target and scrolling to it:
$(document).click(function(evt){
var target = evt.target;
$(window).scrollTo(target, 1000);
});
However, this will scroll to everything that a user clicks on. A better solution is to set up click event handlers on only the anchor tags that you want to scroll to:
$("#source a").click(function(evt){
evt.preventDefault();
var target = $(evt.currentTarget);
$(window).scrollTo(target, 1000);
// More code here...
});
I have a while statement that is echoing about 10 different stories. Every story has a user comment. When clicking the button edit I want one of the functions to hide the user comment. Here is the code I wrote to try and make it happen. Let me know if you think of why this wouldn't work.
<script>
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
</script>
<?php
if (!empty($user_comment))
echo "
<p class='user_comment comment_$story_id'><strong>$user_comment</strong> <a class='edit_story_comment edit_$story_id'>Edit</a></p>";
else
echo "<p id='user_comment_$story_id'><span id='edit_no_story_comment'>Edit</span></p>";
?>
so im gonna ges its becuse of the ankertag is being defined after you are
hocking upp the event with jquery
use jquerys on load event to get around this
$(function() {
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
});
hope this help
(mixing php html and jquery and string concatenation is beautiful btw :D)