jeudi 26 octobre 2017

Ruby on rails 3 - Using checkbox field inside form_for , sending html and json both request in ajax call

I have toggle button on my form and on toggling it i am sending ajax call request to save updated boolean value in the database from controller. but it is sending Html and json request both. I just want to send only one json request. (using rails 3.*)

post_as_premium.html.erb

<%= form_for @editor, url: set_as_premium_reporter_path, remote: true do |f| %>
<div class="editorSettings">
      <div class="premiumCheck">
        <label class="clearfix" for="user_post_premium_permission">
          <span class="checkBoxWrap <%= @editor.post_premium_permission ? 'allChecked' : '' %>">
            <%= f.check_box :post_premium_permission %>
          </span>
        </label>
      </div>
  </div>
<% end %>
     <script type="text/javascript">
        if($("#user_post_premium_permission").parent("span").hasClass('allChecked')){
            $("#user_post_premium_permission").attr('checked', true);
        }else{
            $("#user_post_premium_permission").attr('checked', false);
        }

        $("#user_post_premium_permission").on("change", function(){
            if ($(this).prop('checked')){
                $(this).parent("span").addClass("allChecked");
            }else{
                $(this).parent("span").removeClass("allChecked");
            }
            this.form.submit();
        });
  </script>

2 ] Controller -

 def post_as_premium
   @editor = current_user
 end

def set_as_premium
if params[:editor] && params[:user][:post_premium_permission]
  current_user.update_attributes(post_premium_permission: params[:user][:post_premium_permission])
  respond_to do |format|
    format.js { head :ok }
    format.html { redirect_to post_as_premium_path(current_user)}
  end
end

Aucun commentaire:

Enregistrer un commentaire