Matt Elhotiby
Matt Elhotiby

Reputation: 44066

render a partial after a successful ajax call?

I have this jquery ajax

$.ajax({
 url: "/update_fb_user?fb_uid=" + FB.getSession().uid,
 dataType: 'json',
 success: function(data){
    if(data.user != "none"){
        // here is where i need to render this partial
    }else{
        window.location.href = '/signup';
    }
 }

here is the partial call in the view

<div id="fb_iframe">
<% unless current_user.not_using_facebook? %>
    <%= render :partial => 'fb_iframe' %>
<% end %>
</div>

I was thinkng of just doing fb_iframe, but is there a way to either render the partial or recheck the unless block because the ajax call updates it so that the unless condition is true...any ideas on how to achieve either one or any way of doing this?

Upvotes: 4

Views: 1910

Answers (2)

F&#225;bio Batista
F&#225;bio Batista

Reputation: 25270

Assuming your partial is already on the view (since you said you wanted to 'recheck the unless block'), looks like a reload to the page after the Ajax call succeeds is your solution.

$.ajax({
  url: "/update_fb_user?fb_uid=" + FB.getSession().uid,
  dataType: 'json',
  success: function(data){
    if(data.user != "none"){
      window.location.reload();
    }else{
      window.location.href = '/signup';
    }
  }
});

Upvotes: 4

John F. Miller
John F. Miller

Reputation: 27217

Here is the problem, the partial lives on your server while the JavaScript is run client side. You need to get the rendered html from your server back to the client. How you do this depends on whether the partial depends on your user model.

The two best options I can see are:

  1. Return the partial as part of the json structure the /update_fb_use returns. Then say $("#fb_iframe").html(data.html).

  2. Include the partial in the original page as a JavaScript template using jQuery or Mustache.js. Then, if you have a user, simply render the template.

The problem with approach 2 is that it may be hard to create a JavaScript template until you get enough data from the user. It all really depends on what is in your partial.

Upvotes: 3

Related Questions