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?
There are 3 solutions (that i can think of):
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);
}
You can use something like Moustache or Handlebars. Never used it, so I can't do a proper example. Sorry.
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);
});
});
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With