Reputation: 1049
So, I have 2 follow/unfollow forms in my Rails code. Which are like this
<%= form_tag( {:controller => 'profile', :action => 'unfollow_topic' }) do %>
<%= hidden_field_tag :topic_id, @topic.id %>
<button class="question_button" type="submit">Unfollow</button>
<% end %>
and this:
<%= form_tag({:controller => 'profile', :action => 'follow_topic' }) do %>
<%= hidden_field_tag :topic_id, @topic.id %>
<button class="question_button" type="submit">Follow</button>
<% end %>
And then I have this javascript code:
<script type="text/javascript">
$(function(){
$('#follow form').submit(function(e) {
$.ajax({
url: this.action,
type: 'POST',
data: $(this).serialize(),
success: function(response){ $('#follow').html(response); }
});
return false;
});
});
</script>
My question is how i can return from my controller the appropriate "follow/unfollow" partial for it to be replaced with the response returned.
What I currently have is this, but it doesn't seems to work:
respond_to do |format|
format.html { redirect_to('/' + topic.type + '/' + topic.uri) }
format.js { render :partial => 'unfollow_topic' }
end
But instead if renders the whole page, I believe it's actually responding to the format.html and not the format.js any ideas?
Upvotes: 3
Views: 1688
Reputation: 186
JavaScript:
<script type="text/javascript">
$(function(){
$('#follow form').submit(function(e) {
$.ajax({
url: this.action,
type: 'POST',
data: $(this).serialize(),
dataType: 'html'
success: function(response){ $('#follow').html(response); }
});
return false;
});
});
</script>
controller:
respond_to do |format|
format.html do
if request.xhr?
render :partial => 'unfollow_topic'
else
redirect_to('/' + topic.type + '/' + topic.uri)
end
end
end
Upvotes: 5