Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Rendering JSON object (from AJAX response) into view

I'm using Rails 4 and I'm quite new to JSON objects.

I have a controller:

class UsersController < ApplicationController

 def select_users

   @users = User.all
   respond_to do |format|
     format.html
     format.js {} 
     format.json { 
        render json: {:users => @users}
     } 
   end
 end
end

And a javascript users.js:

$.ajax({
    url:  "/users/select_users",
    dataType: "json",
    data: {
        prezzario: ui.item.value
    },
    success: function(data) { 
        $('#usersList').append(data.users);
    }
});

Now I want to render this collection of users in a div, but I don't know how. In the data response I have in the console the correct data, with an object like this:

{"users":[{"_id":{"$oid":"536cf7b6b8dd181f4b7acf9f"},"children":[{"$oid":"536cf7b6b8dd181f4b7acfa0"},{"$oid":"536cf7b7b8dd181f4b7acfd1"}],"description":"Some description.","name":"My name","user_id":"1"},{...........}]}

I have a partial /users/_users.html.erb with classic users.each and prints of all properties. If I try

$('#usersList').append("<%= render 'users', :locals{ :users => "+data.users+"} %>");

I find in the div #usersList <%= render 'users', :locals{ :users => undefined }%>

I want to create a partial template and use it to render users. How can I do this?

like image 857
Giuseppe Avatar asked May 15 '14 20:05

Giuseppe


2 Answers

There are 3 solutions (that i can think of):

  1. Your controller can render HTML on the backend that you append to your js, like

     class UsersController < ApplicationController
    
       def select_users
         @users = User.all
         render "view", :users => @users
       end
    

    and

     success: function(data) {
       $('#usersList').append(data);
     }
    
  2. You can use something like Moustache or Handlebars. Never used it, so I can't do a proper example. Sorry.

  3. You can render the html in side the success code like

     success: function(data){
       data.users.forEach(function(user){
         $user_html = $("<div class='user'>" + user.name + "<!-- etc --!/></div>");
         $('#usersList').append($user_html);
       });
     });
    
like image 185
negative Avatar answered Sep 17 '22 12:09

negative


You have to $.parseJSON(data); first.

Like

 $.ajax({
    url:  "/users/select_users",
    dataType: "json",
    data: {
       prezzario: ui.item.value
    },
    success: function(data) { 
       var r = $.parseJSON(data);
       console.log(r.users)//This is where Your users are
    }
});
like image 35
Mantosh Avatar answered Sep 21 '22 12:09

Mantosh