skip87
skip87

Reputation: 529

don't understand why ajax isn't updating my button directly

The goal of my ajax is to follow and unnfollow someone . The problem is that when i click on the button follow the resquest is send but i need to refresh the page to the new button Not following see it . How do i make sure that it work directly without refreshing.

<script type="text/javascript">
$(function() {
    $('.ajax_button').click(function() {
        $.ajax({
            type: "POST",
            url: "/" +$(this).attr('name') + "/toggle_follow_via_ajax",
            success: function(msg){
                elm = $('#btn_' + msg);
                if (elm.val() == "Stop Following") {
                    elm.val("Follow");
                } else {
                        elm.val("Stop Following");
                        }
            }
        });
    })
});
</script>

here is the html.erb that generate the button

<div class="button_container">
        <input type="button" name="<%= friend.username %>" id="btn_<%=friend.username %>" class="button ajax_button" 
        value="<% if current_user.is_friend? friend %>Stop Following<% else %>Follow<% end %>"/>
    </div>

Upvotes: 1

Views: 122

Answers (1)

Gwyn Howell
Gwyn Howell

Reputation: 5424

Instead of using the value returned from the server to get a handle to the button, you can get a handle to it before calling the ajax method (since you are already within scope of the button object). Like this:

<script type="text/javascript">
$(function() {
    $('.ajax_button').click(function() {
        var btn = $(this);
        $.ajax({
            type: "POST",
            url: "/" +$(this).attr('name') + "/toggle_follow_via_ajax",
            success: function(msg) {
                var val = btn.val() == 'Follow' ? 'Stop Following' : 'Follow';
                btn.val(val);
            }
        });
    })
});
</script>

I've not tested this code, but it should work

Upvotes: 1

Related Questions