Dave Dave - 3 months ago 8
Ajax Question

How do I prevent Ajax from executing if my user isn't logged in?

I’m using Rails 4.2.7. I have this set up for handling an action is a user clicks on an image on my page

<%= link_to image_tag('disk.png', :alt => 'Save'), my_object_create_path(:id => my_object.id), :class => 'link-save', title: 'Save', :remote => true %>


and then I have this coffee script for dealing with the call after the controller returns …

$('a.link-save').on 'ajax:success', ->
$(this).closest('td').text('Saved')


The problem is, I don’t want the above to execute if my user isn’t logged in. I have this in my controller …

respond_to do |format|
if logged_in? && my_object.save
flash[:notice] = 'Saved successfully'
format.json { render json: my_object, status: :created }
elsif !logged_in?
format.js { render js: "alert('not logged in');" }
else
format.json { render json: my_object.errors, status: :unprocessable_entity }
end
end


How do I prevent my ajax:success from executing if my user isn’t logged in?

Answer

I would modify the view, and only assign the class "link-save" if the user is logged on. The resulting JavaScript will not find the object to add the handler. This will not cause javascript errors because jQuery selectors work fine if they find nothing.

<%= link_to image_tag('disk.png', :alt => 'Save'), 
            my_object_create_path(:id => my_object.id), 
            :class => logged_in? ? 'link-save' : '', 
            title: 'Save', :remote => true %>
Comments