Jquery click function not working when using AJAX - javascript

this is my html code
<input type="hidden" value="<?php echo $rslt['id'] ?>" id="res_id" /> <!-- this line catch post id -->
<div id="likeSec">
<h4><?php echo $rslt['likes'] ?> People Like this</h4> <!-- this line show total likes -->
<?php
$kol=mysql_query("SELECT * FROM tbl_like_recipe WHERE res_id='".$rslt['id']."' && user_id='".$_SESSION['member_email']."'");
$num_rows = mysql_num_rows($kol); // this query check this user already like this post or not
if($num_rows==0){ // if not liked already show like image
?>
<div id="like" style="float:right;"><img src="images/like.png" width="45" /></div>
<?php
}else{ // if already like show unlike image
?>
<div id="dislike" style="float:right;"><img src="images/unlike.png" width="45" /></div>
<?php } ?>
</div>
and this my script
<script>
$(document).ready(function(){
$("#like").click(function(){
var res_id=$("#res_id").val();
$.post("like_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec *").remove();
$("#likeSec").html(cbd)
})
})
$("#dislike").click(function(){
var res_id=$("#res_id").val();
$.post("dislike_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec *").remove();
$("#likeSec").html(cbd)
})
})
})
</script>
When I click 'like' I see it becomes 'Unlike', but if I click on 'Unlike' it doesn't work.
If I then refresh the page and click 'Unlike', it becomes 'Like', but I can not click 'Like' again to make it 'Unlike' again.
What did I do wrong here? please help me someone.

You are generating dynamic elements in your DOM, thus the click event wont be attached due to the lack of delegation, in order to make this work, try the following:
$("#likeSec").delegate('#like', 'click', function(){
var res_id=$("#res_id").val();
$.post("like_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec *").remove();
$("#likeSec").html(cbd)
})
})
$("#likeSec").delegate('#dislike', 'click', function(){
var res_id=$("#res_id").val();
$.post("dislike_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec *").remove();
$("#likeSec").html(cbd)
})
})

Try this
$('#likeSec').on('click','yourdiv',function(){
//Your Code
});

When you receive ajax response, you replace original HTML elements which had events attached with new HTML. Use .on to attach delegated events:
$("#likeSec").on("click", "#like", function(){
var res_id=$("#res_id").val();
$.post("like_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec").html(cbd)
})
})
$("#likeSec").on("click", "#dislike", function(){
var res_id=$("#res_id").val();
$.post("dislike_recipe_prosses.php",{'data':res_id},function(cbd){
$("#likeSec").html(cbd)
})
})

Related

Change height of div with jquery after ajax returns data

I have a div which is always the same height as the div next to it (depending how much content is loaded in that div etc).
This works fine, but now I added a search function using jquery, it stopped working. When I search, the element that is used in the jquery calculation is loaded again. So I tried adding the jquery code inside the ajax callback, but this didn't work either. What should I do?
My code:
$(window).resize(function() {
var contenthoogte = $(".news-content").height();
$(".contenthoogteaangepast").css("height", contenthoogte);
}).resize();
My HTML:
<div class="col-sm-4 padding-zero contenthoogteaangepast">
<form action="ajax/result.php" id="zoeken">
<div class="zoekveld">
<input class="inputzoek" type="text" placeholder="zoeken..." name="zoekwaarde">
<input class="inputbutton" type="submit" value="Zoeken">
</div>
</form>
<div class="downloads">
<h4>Downloads</h4>
<ul>
<li>
- PDF Voorbeeld 1
</li>
<li>
- PDF Voorbeeld 2
</li>
<li>
- PDF Voorbeeld 3
</li>
</ul>
</div>
</div>
<div class="col-sm-8 padding-zero" id="result">
<div class="box large-width-box-w1 full-width-box news-right entry-content news-content">
<?
if($zoekwaarde != ''){
$zoekresultcon = $conn->query($zoekresult);
while($zoekresult = $zoekresultcon->fetch_assoc()){
$zoekresultaten .= '<div class="zoekresultaat"><h4>'.$zoekresult['title'].'</h4></div>';
}
echo $zoekresultaten;
}else{
?>
<h2 class="port-tit contenttitle"><? echo $content['title']; ?></h2>
<?
//Replace img met img src="cms/ zodat je ook tussen de tekst images kan toevoegen
$replaced = str_replace('img src="','img src="cms/',$content['introtext']);
echo $replaced;
}
?>
</div>
</div>
This is what I tried with ajax:
$( "#zoeken" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
zoekvalue = $form.find( 'input[name="zoekwaarde"]' ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { zoekwaarde: zoekvalue } );
// Put the results in a div
posting.done(function( data ) {
$(window).resize(function() {
var contenthoogte = $(".news-content").height();
$(".contenthoogteaangepast").css("height", contenthoogte);
}).resize();
$("#result").html(data);
});
});
It should be changed even without resizing the screen so I also tried copying the code outside the .resize function, but this also didn't change anything.
First things first. You really shouldn't mix languages when programming. Even for a native Dutchie like me, this is very confusing to read. I've replaced all Dutch words for English equivalents.
Like A. Wolff said it's bad to mix events. So let's restructure some things.
First I've removed the window resize and replaced it with a call to resizeContainer. This function handles the resizing of your container. This function is also called in the window resize event.
function resizeContainer() {
var contentheight = $(".news-content").height();
$(".contentheightaltered").css("height", contentheight);
}
$(window).resize(function() {
resizeContainer()
}).resize();
$( "#search" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
searchvalue = $form.find( 'input[name="searchval"]' ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { searchval: searchvalue } );
// Put the results in a div
posting.done(function( data ) {
$("#result").html(data);
// Resize the compagnion container AFTER the data has been updated
resizeContainer();
});
});
This approach means that you don't repeat code, instead bundle it in a function that is called multiple times.
This one worked with me :
$( "#contenthoogteaangepast" ).on( "changeHeight", function() {
$( this ).height($("#.news-content").height());
});
//inside the callback of the request :
$( "#contenthoogteaangepast" ).trigger( "changeHeight" );
or try :
function func() {
$( this ).height($("#.news-content").height());
}
//inside the callback of the request :
func();
I didn't try the second one but it should work.

Trigger JQuery event on ajax response element

I have a problem with event triggering in my codeigniter project. I want to load a table dynamically in my page. This table is returned from my controller through an ajax call. And I want to trigger a click event in a span in that table. I tried this in many ways, but its not working. I am attaching my code here. please help me to find a solution.
controller :
$str = '<table>
<tr>
<td class="cost date" id="date_'.$request['SupplyID'].'">
<span class="editable" style="display: none;">
<input type="text" class="expiry" autocomplete="off" data-date-id="date_'.$request['SMSSupplyID'].'">
</span>
<span class="cnt" style="display: inline;">Choose</span>
</td>
</tr>
</table>';
echo $str;
script in view :
function loadmore()
{
var url;
url = '/SMS/SMS/loadMoreRequests';
$.ajax({
type: 'post',
url: url,
data: {
limit:val
},
success: function (response) { console.log(response);
$("#requestListTable").html(response);
val +=10;
}
});
}
$('.date').find('.cnt').on('click', function(){
console.log(1); // for testing
});
I tried the following changes, but no use
1)
$('.date').find('.cnt').live('click', function(){
console.log(1); // for testing
});
2)
$('.date').find('.cnt').click(function(){
console.log(1); // for testing
});
$("container for the table").on("click", ".cnt", function() {
});
You can use the event delegation for this. Bind the event to a parent element which is present on the dom on document ready. Or you can simply use,
$("body").on("click", ".cnt", function() {
});
You can try this
$(document).find(".cnt").on("click",function(){
console.log(1); // for testing
});
You need to delegate the Event to the dynamically created elements.
$(document).on('click','.cnt',function(){
alert("Processing comes here");
});

$('#notificationClick').click not working

so I'm trying to make this works here is the jquery+php.
When I try to trigle the click in jquery it doesnt even does the "alert()".
PHP(Updated):
$MSG_Notification_sql = mysqli_query($Connection, "SELECT * FROM notifications WHERE user_id='".$bzInfo['id']."'");
while ($MSG_Notification_row = mysqli_fetch_array($MSG_Notification_sql)){
$MSG_Notification_rows[] = $MSG_Notification_row;
}
foreach ($MSG_Notification_rows as $MSG_Notification_row){
$bzWhen = date('d-m-Y H:m:i', strtotime($MSG_Notification_row['when']));
echo '<form method="POST">
<div class="notificationClick notification-messages info">
<div class="user-profile">
<img src="assets/img/profiles/d.jpg" alt="" data-src="assets/img/profiles/d.jpg" data-src-retina="assets/img/profiles/d2x.jpg" width="35" height="35">
</div>
<div class="message-wrapper">
<div class="heading"> '.$MSG_Notification_row['title'].'</div>
<div class="description"> '.$MSG_Notification_row['description'].' </div>
<div class="date pull-left"> '.$bzWhen.'</div>
</div>
<input name="notificationID" value="'.$MSG_Notification_row['id'].'" style="display: none" />
<div class="clearfix"></div>
</div>
</form>';
}
Javascript(Updated):
$(document).ready(function(){
$('.notificationClick').click(function(event){
alert('Ok');
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = $('#notificationClick').serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/notifications/msgs_del.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
window.location = '/?page=messages&sub=inbox&bx=preview&id='+ data.notificationID +'';
});
event.preventDefault();
});
});
Can anybody help me please? I'm trying to complete this but nothing :(
First as the others say, ids need to be singular. So use the class you already have. Now inside, you need to use the current form that you clicked on, not all the forms.
$('.notification-messages').click(function(event){ //<-- change to class
var formData = $(this).closest("form").serialize(); //change to this
...
If you are loading these dynamically, you need to use event delegation
$(document).on("click", '.notification-messages', function(event){
var formData = $(this).closest("form").serialize();
...
You can concatenate the timestamp to your id to make it unique (separated by an _ if you like) and change your selector for the click event to $('[id*="notificationClick_"]')
On the other hand, you might want to use a class instead, that's what it's there for:
$(".notification-messages")
You're using ID, you can only bind click to 1 id not multiple ids.
You should use the class to bind the .click function.

Codeigniter ajax call does not work properly

For example if I click 'vote up' button it successfully adds vote for the first post and displays the result in span element with class="rate_votes", but it also displays the same result in all the span elements with same class because of the following line:
$(".rate_votes").text(rate); //
How can I avoid that?
If I use
$(this).text(rate); //
it will not work properly because it does not know which span element to select. Could you help me please.
Here is my view:
<div>
<?php
foreach($results as $row){
$id = $row['id'];
$rate = $row['rate'];
?>
<div>
<?php
$data = array(
'name' => $id,
'class' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
?>
<span class="rate_votes" >
<?php echo $rate; ?>
</span>
</div>
</div>
Here is my JS file:
$(document).ready(function() {
$(".rate").click(function(){
var self = this;
$(self).attr("disabled", true);
var id_like = $(self).attr("name");
$.post('filter/get_rate', { id_like: id_like }, function (data) {
var my_obj = data;
$.each(my_obj, function (i) {
var rate = my_obj[i].rate;
$(".rate_votes").text(rate); //
$(self).text("Voted!");
});
}, "json");
});
});
This has nothing to do with codeigniter :)
You bind the click event to an ID, #rate but that ID appears multiple times.
$data = array(
'name' => $id,
'id' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
use a class instead.
When you select an ID that appears multiple times, only the first one is selected, thus only the first button works.
EDIT
Your comment sounds a bit strange, Given this code for example :
HTML:
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
Javascript/Jquery
$('.foo').click(function() { $(this).remove() });
The above code only removes the specific div being clicked, That is the event is only fired once and for that element only.
Doublecheck your javascript.
You have used:
$("#rate").click(function(){...})
Here "#rate" is an id and an id must be unique, use class like .rate. If you have multiple elements with same id on the page then only the first element of the page will be counted. So the following code is registering the click handler only on the first element with id rate:
$("#rate").click(function(){
//...
});
Give your elements a class instead, for example:
<button class='rate'>Rate</button>
<button class='rate'>Rate</button>
So this code will work on every button click:
$(".rate").click(function(){
var id_like = $(this).attr("name");
$(this).attr("disabled", true); // disables the current button
$('.rate').attr("disabled", true); // disable all the buttons with class rate
//...
});

Colorbox modal of any URL

I'm trying to create a modal that opens any URL, where the a tag has a specific class.
In the colorbox docs it has this as an example:
// ColorBox can accept a function in place of a static value:
$("a.gallery").colorbox({rel: 'gal', title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
My HTML structure is:
" class="modal" rel="gal">
<h2 id="post-<?php the_ID(); ?>"><?php the_title(); ?></h2>
<div class="entry">
<?php the_excerpt(); ?>
</div>
</div>
and my JS is:
jQuery(".modal").colorbox({rel: 'gal', title: function(){
var url = jQuery(this).attr('href');
return 'Open In New Window';
}});
But it's just not triggering - I'm not getting any console JS errors - can anyone see what's wrong here?
You are using the colorbox() method on <div> elements, which are not valid elements for that method. This method may only be used on <a> elements.
Totally misinterpreted the function - if you are trying to do what I outline in the opening post then use the iframe functionality.
e.g.
jQuery(function () {
jQuery(".modal").colorbox({iframe:true, innerWidth:425, innerHeight:344});
})
parent.$.colorbox.resize({ width: 460, height: 130 });

Categories