C
C
caution2014-08-14 19:43:38
JavaScript
caution, 2014-08-14 19:43:38

How to remove the ability to jump to actions that work with ajax + json through the browser line?

In general, below is my code that implements the loading of the book add form using ajax and json, the problem is that if you go through the browser along the path host_hame/books/new, then the browser renders what the new action returns: Can someone
21ebea00f64b4a56a92356d39b54c8ca.png
tell me how to prevent the rendering of this action when passing through a line in the browser?
index.html.erb

<%= link_to 'New Book', new_book_path, remote: true, class:"new_book" %>
<div class="lol"></div>

books_controller.rb
def new
    @book = Book.new
    form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
    render :json => { :form_html => form_html }
  end

book.js
$(document).on('ajax:success', '.new_book', function(e, data, textStatus, xhr) {
  $('.lol').append(data.form_html)
})

I have an idea to do it like this:
books_controller.rb
def new
    @book = Book.new
    form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
    respond_to do |format|
      format.json { render :json => { :form_html => form_html } }
      format.html { redirect_to root_path }
    end
  end

But I think it's not very beautiful, and right. And in general, is it advisable to render such forms through a regular render and hide with jQuery ?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Dmitry Demin, 2014-08-14
@keksmen

I think you should just change the http method from GET to POST in the router module config. This will automatically weed out most curious users.

L
Lesha Kiselev, 2014-08-14
@Yakud

I do not know ruby, but the algorithm is very simple.
Before the output, it is enough to check whether the request is really ajax.
Looks like your solution is here: stackoverflow.com/questions/366311/how-do-you-hand...

_
_ _, 2014-08-14
@AMar4enko

Read here
railsadventures.wordpress.com/2012/10/07/routing-o...

M
mayorovp, 2014-08-15
@mayorovp

Such a question: in fact, why do you need it? What is the problem with displaying these jasons in the browser? Just don't link to them and regular users will never see them.

A
Andrey Shchetinin, 2014-08-28
@draedful

You can register in the routing (well, or something like that)
It is possible in the controller

class BooksController < ApplicationController
  before_action :access_check, only:[:new]
  def new
    @book = Book.new
    form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
    render :json => { :form_html => form_html }
  end
  private
    def access_check
      unless request.xhr?
         redirect_to :root_path
      end
    end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question