ajax - Rails: return only json -
in app there list of items can upvote. want make these votes ajax calls.
this view:
<ul class="list-groups"> <% @questions.each |question| %> <li class="list-group-item"> <%= link_to question.description, question_path(question) %> <%= form_for(question, :url => url_for(:controller => 'vote', :action => 'vote'), method: :post, html: { class: 'form-inline' }) |f| %> <%= f.submit 'up vote', class: "btn btn-default" %> <%= f.hidden_field :id, :value => question.id %> <% end %> </li> <% end %> </ul> and method it:
class votecontroller < applicationcontroller respond_to :json def vote question_id = params[:question][:id] user_id = current_user.id vote = vote.where(["question_id = :q", { q: question_id }]).where(["user_id = :u", { u: user_id }]) respond_to |format| if vote.nil? @vote = vote.new @vote.question_id = question_id @vote.user_id = user_id @vote.save format.html { render '/home/index' } format.json { render :json => { :status => 'ok' } } else format.html { render '/home/index' } format.json { render :json => { :status => 'failed', :msg => 'you voted' } } end end end end if don't include format.html { render '/home/index' } getting error:
actioncontroller::unknownformat in votecontroller#vote but don't want render page again, loading pieces of html change after action jquery , ajax.
how can respond json?
use respond_with instead of respond_to in controller action.
respond_with |format| respond_to @ top of controller designed work respond_with in controller action, whereas respond_to in controller action ignores respond_to you've defined @ top of controller.
also make sure making remote call, instead of normall 1 if want request go through ajax.
<%= form_for(question, :url => url_for(:controller => 'vote', :action => 'vote'), method: :post, remote: true, html: { class: 'form-inline' }) |f| %> note remote: true part added argument form_for helper.
Comments
Post a Comment