Yax Yax - 6 months ago 13
PHP Question

Prepending and overwriting a class with AJAX response in PHP

I am working on a site that has like button attached to posts made by users. I want whenever a user likes a post, the like count of that post should be replaced with current one but it is affecting the whole post.

This is code for the Like button

echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown'
value='".$post_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span>
<span class='glyphicon glyphicon-heart'></span></button>";


And this the AJAX that gets fired whenever the button is clicked:

$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
alert ("User ID is " + user_id + " Post ID is " + post_id);
$('.likecount').html( msg );
});
});


And this is the
echo
result from
likes.php
after update the database:

echo "<span class = 'likecount'>". $count . "</span>";


The database side is working just fine.

Answer

welll your are replacing the html inside the span with a <span class = 'likecount'> again.

why don't you just echo $count from you ajax called page and only this will be replaced in success function..

try this

in you likes.php file

 echo $count; //just return the count

no changes in ajax ..

//same
request.done(function( msg ) {
 alert ("User ID is " + user_id + "  Post ID is " + post_id);              
    $('.likecount').html( msg ); 
});

that should do the trick..

you can also change you datatype to JSON and send json as response in your php ..

updated

 $(".murconform").submit(function(e){
    return false;
 });

 $(".mlike").click(function () {
   var $this=$(this);
   var post_id = $(this).val();
   var user_id = $(".user_id").text();
   var request = $.ajax({
       url: "likes.php",
       type: "POST",
       data: { post : post_id , user : user_id },
       dataType: "html"
   });

   request.done(function( msg ) {
     alert ("User ID is " + user_id + "  Post ID is " + post_id);              
        $this.prev('.likecount').html( msg ); 
     });
   });  
Comments