If use Rails framework with ajax request, this way in controller can send data back to front-end:
def get_posts
@posts = Post.where(user_id: params[:user_id].to_i)
if request.xhr?
render :json => {
:posts => @posts
}
end
end
Front-end can catch it:
$.ajax({
type: "GET",
url: "<%= get_post_path %>",
data: {user_id: $("#user_id").val()},
success: function(data, textStatus, xhr) {
alert(data.posts);
//...
}
Then in Phoenix framework, how to send data back to front-end?
I saw this guide from official docs:
It's method is using render("page.json", %{page: page})
to send data but I don't want to create a json file.
So is it possible to send data back to front-end like Rails way?
It is possible. You have quite a few steps though... First, your router needs to pipe the request so it accepts json. Something like this:
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", TodoWithAuthWeb do
pipe_through :api
resources "/posts", PostController, except: [:new, :edit]
end
Then your controller action should render a .json view as
render(conn, "show.json", post: post)
And this show.json
view would be something like
def render("show.json", %{post: post}) do
%{data: render_one(post, PostView, "post.json")}
end
def render("post.json", %{post: post}) do
%{id: post.id,
title: post.title}
end
Or something like that. You could just use the phx tool to generate an entire resource for you tho... For exemple, generating an user/controller/views/etc
mix phx.gen.json Authentication User users email:string encrypted_password:string
Where Authentication
is the "package" name
User
is your model name on the codebase
users
is your collection name on the db
and the others args are similar to the rails generators I guess
There are some guides on the web such as Building a Trello copy with Phoenix and React
You can also check my simple todo-list phoenix repo on github so you can see the basics TodoApp example (its pretty dull tho)