jQuery selectors after dynamic reload, and $(this) - javascript

I need some help. I load a list of entries in a div every 5 seconds. Each entry is a div and has a unique ID. Like this:
<div class="entry">
<div class="textbox">
<p class="entry-text">
<?php echo $text;?>
</p>
</div>
<div class="infobox">
<p class="date"><a #<?php echo $id;?> id="<?php echo $id;?>" href="gen_details.php?id=<?php echo $id;?>"><?php echo $t;?></a> </p>
<p class="ip"><?php echo $ip;?></p>
</div>
These, as I said are loaded each 5 seconds. I'm adding a details page for every entry, with this:
$('.date a').click(function () {
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
return false;
});
This works perfectly fine, until it reloads. It seems to lose the handle for the a href and instead of doing the procedure it goes to gen_details.php
I have tried to use .on() but I don't know how would I get the ID of the entry using .on(), as I cant use $(this) (afaik).
I hope I explained my problem at least half-well. English is not my first language so it wasn't that easy.
Thanks in advance.

Try this selector
$('div').on('click', '.date a', function () {
This will delegate the event to its parent div. So it should work for dynamically created elements as well.

Live click event bind event handler to element even after you reload some element. Default click event bind to element when a page load once you reload that element then it also delete event handler of that element.
works on till jquery 1.7 version.
$('.date a').live('click',(function (e) {
e.preventDefault()
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
});
//when jQuery > 1.7 then used this method
$('body').on('click' '.date a',function () {
//call
});

Related

jQuery select every time first element

HTML:
<div class="vote" id="<?php echo $id; ?>">
jQuery:
$('.vote').on('click', function() {
var div = $(".vote").attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(".vote").attr('id')
},
success: function(data) {
alert(div);
}
});
});
this works, but div var it's always first element - and runs twice (two divs with vote class).
I use AJAX for displaying results (divs with vote class) also.
Why is this happening and how can I fix?
You need to use this, which refers to element which invoked the element.
var div = $(this).attr('id'); //this.id;
When you are using $(".vote").attr('id') it will always return you id of first element.
As you are using id to store custom data. I would recommend you to use data-* prefixed custom attribute which can be fetched by using .data()
<div class="vote" data-id="<?php echo $id; ?>">
Then you can use
var id = $(this).data('id');
You need to use current elements clicked context this:
var div = this.id;
Replace your $('.vote') to $(this) like this below:
$('.vote').on('click', function() {
var div = $(this).attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(this).attr('id')
},
success: function(data) {
alert(div);
}
});
});
Use this.id instead of $('.vote').attr('id'), because javascript will get the first id he founds if you use $('.vote').attr('id')

Jquery removing issue divs still remains

Yesterday I coded a Commentbox in PHP, HTML and ajax. The ajax part gives me the opportunity to delete a comment without refreshing the page. The way I do this, is that I give each and every comment (div) a unique id via the database. So let us for example say that in my mysql database this is how a comment looks like:
Username: blabla<br>
Comment: haha this is so funny<br>
id: 52
This will be printed out in the html page likes this for example:
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment">Delete the comment here!</div>
</div>
AND THEN!
Comes the ajax part which is coded something like this:
$(document).ready(function(){
$(".deleteComment").click(function(){
//Getting the id of comment
id = $(".deleteComment").attr("id");
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
});
This works fine when deleting the first comment. But it WONT LET ME DELETE OTHER COMMENTS UNLESS I REFRESH THE PAGE >.<. The first comment can be perfectly deleted without refreshing the page, but when I want to delete other comments I have to refresh the page multiple times.
How do I solve this?
The code in your document ready event would work properly only for the first click. In order to get this work, you must have an on click event registered within the tag.
Example :
<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>
function DeleteMe(id)
{
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
}
If the on click on a div does not work, you can use an anchor tag (Delete here) instead.
.deleteComment is child of <div class="commentStyle".., so you can select it with parent() selector:
var id = $(this).parent().attr("id");
Or more specifically:
var id = $(this).parent('.commentStyle').attr("id");
Looks like you need to get the id from the parent element first and then target the child, the element you clicked, to hide the comment from it after the ajax request returns success:
$(".deleteComment").click(function(){
var id = $(this).parent().attr("id");
var child = $(this);
$.ajax({
type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
child.hide();
// or if you want to delete the entire element with the id of X
// child.parent().hide();
}
});
});
There are few changes which need to be done in your code.
First of all add ID tag to the inner div.
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here! </div>
</div>
Secondly use this
id = $(this).attr("id");
instead of...
id = $(".deleteComment").attr("id");
Thirdly change the ajax call like this:
$.ajax({
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id
}).done(function(){
$("#" + id).hide();
});
Hope this works for you, if not just reply me.

click event on dynamic li elements

Updated the question as per #Jonathan Kuhn's feedback and it works like a charm
I am building a messaging system for my web application.
where the users should be able to communicate with me via messages (ajax)
I am being able to append <ul> with additional <li> from jQuery
$('#send').click(function(e){
e.preventDefault();
var reply = $('#reply').val();
var project_id = 44; // just for reference
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>messages/send",
data:{ msg:reply, project_id:project_id },
success: function (response) {
if(response=="success"){
$(".messages").append('<li class="message" id="message">'+reply+'<a id="delete">delete</a></li>');
var clearText = "ture";
}else{
}
}
});
Which is working perfectly fine. But I am having problem while deleting the dynamically added list element.
I tried bind() and on() jQuery functions but as I am not much good at it, I am facing a lot of issues.
$("#messages").on('click', '#delete', function(event) {
event.preventDefault();
var id = 22 ; // just for reference
$.post( "<?php echo base_url(); ?>messages/delete", { type:'single', id:id } )
.done(function( data ) {
});
$(this).closest('li').remove();
});
My HTML structure is as below
<ul class="messages" id="messages">
<li class="message" id="message">sdaghds<a id="delete">delete</a></li>
</ul>
You have id="#messages" on the <ul>. Remove the # and then the .on one should work.
Also, ids are supposed to be unique throughout the page. So you shouldn't have multiple message ids throughout. If you need multiple, use classes. Remove the id from the <li>.

How to use data-toggle with Ajax and PHP

I am using Bootstrap (which is heavily modified) and love the use of data-toggle. My current script is pretty straight forward, it's an image upload script. I use the following code to list images from the database:
$stmt = $db->query('SELECT * FROM img_slider ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<li>
<div class='thumbnail removable'>
<div class='remove' id='{$row['id']}' data-toggle='remove'></div>
<img src='../{$row['path']}'>
</div>
</li>"
;}
Notice data-toggle='remove' - This function works great removing images statically, but what say I want to remove the images in the database? I understand the best method would be to utilise Ajax. Here is what I mean:
My PHP file delete.php:
$id = $_REQUEST['id'];
$db->beginTransaction();
$st = $db->prepare('DELETE FROM img_slider WHERE id = :id');
$st->execute(array(':id' => $id));
$db->commit();
I am trying to execute this with the following jquery/ajax:
$("a[data-toggle=remove]").click(function()
{
var image_id = $(this).attr('id');
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id,
});
});
Any help would be greatly appreciated! I just don't know how to utilise bootstraps data-toggle with PHP, tried search for the solution, came up empty handed. Here is an image of how the image upload works:
If it is the selector that is the problem, tt should be
$('div[data-toggle="remove"]').click(function() {
but if it is click on the image you mean
$('div[data-toggle="remove"]').next().click(function() {
Edit. I just tested your question like so :
<div class='thumbnail removable'>
<div class='remove' id='27' data-toggle='remove'></div>
<img src='1.gif'>
</div>
$('div[data-toggle="remove"]').next().click(function() {
var image_id = $(this).prev().attr('id');
alert(image_id);
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id
});
});
alerts 27 and and try to XHR with id: 27.
If it is click on the data-toggle <div>
$('div[data-toggle="remove"]').click(function() {
var image_id = $(this).attr('id');
Take a look at jQuery function ON: http://api.jquery.com/on/
The issue is you are binding the click event at load, when you are loading elements in to the page async then they will not events binded. On should bind the events now and in the future.
$("body").on( "click", ".remove", function() {
// Remove stuff
});

Dynamically removing elements from different div

I have the following code:
<div id='a'>
</div>
....
....
<div id='b'>
</div>
combined the script:
$.ajax({
type:'POST',
url:'grouplist.php',
async:false,
dataType:'json',
cache:false,
success:function(result)
{
var $ni=$('#a');
$.each(result,function(key,value)
{
var $button=$('<input></input>',{
'type':'button',
'id':key,
'class':'button',
'value':value
}).appendTo($ni);
});
}});
This creates buttons in the div with a dynamic id. Now I am dynamically adding elements into div with id b if I click on one of these buttons as follows:
$('#a').on('click','.button',function(){
$('.hmm').remove();
var x=$(this).attr('id');
$.ajax({
type:'POST',
url:'groupmsg.php',
async:false,
data:'id='+x,
dataType:'json',
cache:false,
success:function(result)
{
var $na=$('#groups');
$.each(result,function(key,value)
{
var t_msg=value[0]+":"+value[1]+"\t"+value[2];
var $p = $('<p></p>'{'id':'msg'+key,'class':'.hmm'}).html(t_msg).prependTo($na);
});
}
});});
I am unable to remove the elements of div#b using $('.hmm').remove();. Can someone help me in this regard?
There is an error in your code, should be:
var $p = $('<p></p>',{'id':'msg'+key,'class':'hmm'})
No dot (.) should be used when setting class.
Seems like you are attaching click event to the div with id=a and clicking on button which is created inside another element. Try to attach click event to document instead.
$(document).on('click','.button',function(){
// ...
});

Categories

Resources