How to pass data from controller to view using ajax in rails

I posted similar questions twice today

how-to-use-local-or-instance-variable-in-ruby-code-in-coffeescript-in-haml-templ

ajax-in-rails-returns-alway-error-callback

I am confused about these issues, let me ask.

I am using ajax in haml to reload the data portion of the page from the 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 the data could pass through the @model instance variable from the controller, but that couldn't.

Second, I tried to get data from the view ajax response data (_partial.html.haml) using jQuery.

The callback and response are returned correctly as text.

How can I pass data to view from ajax response data or are there other ways?

Sorry for my sloppy english. Hope someone can guide me.

Thanks in advance!

+3


source to share


1 answer


You can set the ajax request to /posts/gaga.json

and in your controller gaga method:

respond_to do |format|
  format.html
  format.json { render :json => @model }
end

      

You might want to prepare a viewfile gaga.html.haml

if you also want /posts/gaga

non-ajax access, or just delete format.html

if you're only going to respond to json.


To clarify, I see that you want to reload the partial request after ajax. Therefore, 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 in 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)

      

+2


source







All Articles