Huy
Huy

Reputation: 11206

How to render a partial from controller after making an ajax call

I am trying to render a partial after I make an AJAX request to a method in my controller. Here is my current AJAX call:

$('.savings_link').click(function(event){
 $.ajax({
    type: 'GET',
    url: '/topics/savings_easter_egg',
    data: {
      savings: data[key]['saving']
    } ,
    dataType: 'json',
  });

 event.preventDefault(); // Prevent link from following its href
});

This call currently works and it hits my controller method where I try to return and render a partial.

def savings_easter_egg
  @savings = params[:savings] if params[:savings]

  return render :json => {
    :html => render_to_string({
      :partial => "topics/savings",
      :locals => { :savings => @savings }
    })
  }
end

Using firebug, I was able to get the response:

{"html":"<p>Hi</p>"}

which reflects my partial topics/savings, but the page does not reload or display my partial.

However, I want to actually redirect or render (display) the actual partial. Any advice?

Upvotes: 1

Views: 609

Answers (1)

rajesh kakawat
rajesh kakawat

Reputation: 10896

you code should be like this

$.ajax({
 type: 'GET',
 url: '/topics/savings_easter_egg',
 data: {
  savings: data[key]['saving']
 },
dataType: 'json',
  success: function(data) {
    $('your div').html(data.html);
 }
});

you have to use that response in your success function , just add to your div done above.

Upvotes: 2

Related Questions