Question

I'm implementing a voting system and I when I want to update the number of votes using AJAX, I refresh the count of all the publications. But I cant to refresh only one publication. See my HTML:

@foreach($publications as $publication)
<li class="like-publication">

 <span>{{HTML::image(URL::to('img/widgets/likesocialmeet.png'),'Like')}}</span>

 <span class="votes">
   {{Publication::find($publication->id)->profilepublicationvotes->sum('vote')}}
 </span>

 {{ Form::open(array('url' => 'profilepublicationvotelike', 'class' => 'vote_ajax')) }}

 <input type="text" id="disabledTextInput" style="display:none" name="vote" value='1'>
 <input type="text" id="disabledTextInput" style="display:none" name="user_id" value="{{ Auth::user()->id }}">
 <input type="text" id="disabledTextInput" style="display:none" name="publication_id" value="{{ $publication->id }}">

 {{ Form::submit('vote', array('class' => 'button expand round')) }}

 {{ Form::close() }}

</li>
@endforeach

And my javascript (AJAX):

$(document).ready(function() {
   var form = $('.vote_ajax');
    form.bind('submit',function () {
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            complete: function(data){
            },
            success: function (data) {
                $('.success_message').hide().html('');
                    $(form)[0].reset();
                    console.log("working");

                    $('.votes').text( data );
            },
            error: function(errors) {
                    alert('Something went to wrong.Please Try again later...');
            }               
        });
   return false;
   });
});
Was it helpful?

Solution

You are selecting all <span class="votes"> by using

$('.votes').text( data );

You need to limit it to just the sibling of the form

var votes = $(this).prev('.votes');
votes.text( data );

So your javascript would look like -

$(document).ready(function() {
   var form = $('.vote_ajax');
    form.bind('submit',function () {
        //get the sibling vote
        var votes = $(this).prev('.votes');
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            complete: function(data){
            },
            success: function (data) {
                $('.success_message').hide().html('');
                    $(form)[0].reset();
                    console.log("working");

                    // update just the sibling vote
                    votes.text( data );
            },
            error: function(errors) {
                    alert('Something went to wrong.Please Try again later...');
            }               
        });
   return false;
   });
});

jsFiddle Example - http://jsfiddle.net/GhMfM/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top