Reputation: 1221
I posted today similar questions two times
how-to-use-local-or-instance-variable-in-ruby-code-in-coffeescript-in-haml-templ
ajax-in-rails-returns-alway-error-callback
I'm confusing about these issues please let me ask.
I'm using ajax in haml to reload a part of page with data from controller.
Please see my code.
.html.haml
= render 'layouts/partial' #This is partial. I want to reload this part
:coffee
$('input#field').change ->
$.ajax
url: '/posts/gaga'
type: "POST"
dataType: 'text'
error: (jqXHR, textStatus, errorThrown) ->
alert "error"
success: (data, textStatus, jqXHR) ->
alert "success"
$('div.kore').html('#{ j( render( 'layouts/partial' ) )} ');
posts_controller.rb
def gaga
@model = Model.new("blabla")
render :text => @model
end
_partial.html.haml
- if @model
= @model.html_safe
- else
= "No data"
First, I thought data can be get through @model instance variable from controller but it couldn't.
Second, I tryed to get data from ajax response data to view(_partial.html.haml) with jQuery.
Callback and response return correctly as text.
How do I pass data to view from ajax response data, or is there other ways?
Sorry for my sloppy English. I hope someone give me the clue.
Thanks in advance!
Upvotes: 3
Views: 2826
Reputation: 192
You can set the ajax request to /posts/gaga.json
and in your controller's gaga method:
respond_to do |format|
format.html
format.json { render :json => @model }
end
You may want to prepare gaga.html.haml
view file if you intend to also access /posts/gaga
not via ajax, or just remove format.html
if you only intend to respond in json.
To clarify, I see you want to reload the partial after ajax request. So rather than:
$('div.kore').html('#{ j( render( 'layouts/partial' ) )} ');
you can do something like this:
# inside gaga methods
format.json do
render(json: {
view: render_to_string(partial: 'layouts/partial', layout: false)
})
end
Now inside your view:
= render 'layouts/partial' #This is partial. I want to reload this part
:coffee
$('input#field').change ->
$.ajax
url: '/posts/gaga.json'
type: "POST"
error: (jqXHR, textStatus, errorThrown) ->
alert "error"
success: (data, textStatus, jqXHR) ->
alert "success"
$('div.kore').html(data.view)
Upvotes: 3