JSON post method in ruby on rails - ruby-on-rails

I want to get data from client side,and display in my ror website using post method in create method,how to write the function for fetching data from client side(android) to ror.
def create
#post = Post.new(params[:post])
data_json = JSON.parse request.body.read
#respond_to do |format|
if #post.save
flash[:notice] = "Prayer Successfully created."
#posts = Post.paginate(page: params[:page],:per_page => 5)
#post = Post.new(data_json)
#post.save
#format.json{ render :json => #post, :status => :created }
else
flash[:notice] = "Error"
#posts = Post.paginate(page: params[:page],:per_page => 5)
#format.json{ render :json => #post, :status => :created }
end
end

There is not enough data in your question but ill try to help you.
Your client-side logic should look like that (jQuery code):
$("#some_button").bind("click", function(event){
$.ajax({
type: "POST",
url: "/bla-bla/create",
data: { my_param: JSON.stringify(my_data) }
});
});
And action of controller that match to route /bla-bla/create:
def create
my_var = JSON.parse(params[:my_param])
...
#do what you want with "my_var"
Hope it'll help you!

Related

How to get the result when calling Ajax function

I need to get the email-id of the client when im clicking the person
name if his email-is is exist in db means by default it should need to
show
$("#user_employee_id").change(function(){
alert(1);
var user_id = $(this).val();
$.ajax({
type: "GET",
url: "/users/emailcheck",
data: { id: user_id }
}).success(function(res){
console.log(res);
$("#user_email").val(res.data["user"]["email"]);
});
});
controller.rb
def emailcheck
#user = User.find_by(id: params[:id])
if #user.present?
render :json => {:user => #user.to_json(:only => [:email]) }
end
end
After doing this also im not getting email can any one suggest me im
wrong, i need tan email-id when im clicking the person, i have 1400
data every one is having email-id please help me out how to get
corresponding employee name when im clicking i need to get thier mail
id bydefalut in mail-id textbox
Change the line in ajax
$("#user_email").val(res.data["user"]["email"]);
With
$("#user_email").val(res.email);
And in controller:
def emailcheck
#user = User.find_by(id: params[:id])
respond_to do |format|
if #user.present?
format.json { render json: {:email => #user.email} }
else
format.json { render json: {:email => " "} }
end
end
end

How to use Post method in def create action in ruby on rails for fetching data

I want to fetch data from client side to ruby on rails by using post method in create action in my controller.But i dont know how to do for getting data from client side in def create action.How to create the api for to get data from client side.
Postcontroller.rb
class PostsController < ApplicationController
respond_to :json, :xml
before_filter :load
def load
if signed_in?
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
#my_post = current_user.posts.new
end
#posts = Post.paginate(page: params[:page],:per_page => 10)
#post = Post.new
end
def index
#posts = Post.all
respond_with(#posts) do |format|
format.json { render json: #post_names = {:post => #posts.as_json(:only=> :content)} }
end
end
def show
if signed_in?
#post = Post.find(params[:id])
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
current_user.vote_for(#post)
else
#post = Post.find(params[:id])
Guest.find(1).vote_for(#post)
end
#posts = Post.paginate(page: params[:page],:per_page => 10)
#guest = Guest.new
#user = User.new
#users = User.paginate(page: params[:page],:per_page => 10)
end
def create
#post = Post.new(params[:post])
respond_to do |format|
if #post.save
#posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: #post, status: :created }
else
#posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: #post.errors, status: :unprocessable_entity }
end
#guest = Guest.new
#users = User.paginate(page: params[:page],:per_page => 10)
end
end
def my_prayer_create
#my_post = current_user.posts.new(params[:post])
#post = Post.new(params[:post])
#guest = Guest.new
#user = User.new
#users = User.paginate(page: params[:page],:per_page => 10)
if #my_post.save
flash[:notice] = "Prayer Successfully created."
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
else
flash[:notice] = "Error"
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
end
def edit
if signed_in?
#my_post = current_user.posts.find(params[:id])
else
#post = Post.find(params[:id])
end
end
def update
if signed_in?
#my_post = current_user.posts.find(params[:id])
if #my_post.update_attributes(params[:post])
flash[:notice] = "Prayer Successfully updated."
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
else
#post = Post.find(params[:id])
end
end
def destroy
if signed_in?
#my_post = current_user.posts.find(params[:id])
#users = User.paginate(page: params[:page],:per_page => 10)
#guest = Guest.new
#my_post.destroy
flash[:notice] = "Prayer Successfully destroyed."
#my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
end
For my controller how can i fetch data from client side.from this only i have to write the url in my client side also like this "http://localhost:3000/posts"
You want to create a method called new
Get all the user inputs in new method and pass it to create method.
new method:
def new
#post = Post.new
end
create method:
#post = Post.new(params[:post])
params[:post] pass all params and save it by #post.save.
Read rails doc for CURD operations first.
EDIT:
in routes.rb:
match '/action' => "controller#action"
write view file for new method to get use input in "views/controller/new.html.erb"
it seems if post saved successfully you will get created post. but if save fails then you are facing some posts
#posts = Post.paginate(page: params[:page],:per_page => 10)
but responding using :
format.json { render json: #post.errors, status: :unprocessable_entity }
So if you want to get some posts if post save fails then it has to respond_with #posts
I got solution for my question,what to use correct params in def create action
def create
#post = Post.create(params[:post])
##post = Post.create(:content=>params[:post][":content"],:title=>params[:post][":title"])
respond_to do |format|
if #post.save
#posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: #post, status: :created }
else
#posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: #post.errors, status: :unprocessable_entity }
end
#guest = Guest.new
#users = User.paginate(page: params[:page],:per_page => 10)
end
end
the params should be same as like the client side given parameter also.
To be precise and exact .. thats the style the normal ruby on rails crud operations follow.
let me be clear..
If you want to create a record in table USERS lets say fields are "name" and "age"
the params in the client side need not be same as the fields of the table.
In the above case we have handle the saving in controller,framework don't take of it.
say on client side 'x' for name and 'y' for age
then the params built in the client side and passed to server is say params=>{:post=>{:x=>"siva", :y => "23"}}
In the controller.
user=User.new
user.name=params[:post][:x]
user.age=params[:post][:y]
user.save

How to use rails post method to get data from client side(android)

I want to use post method for getting data alone from client side,How to use post method in def create function for getting data alone.
post controller.rb
def create
#post = Post.new(params[:post])
if #post.save
flash[:notice] = "Prayer Successfully created."
#posts = Post.paginate(page: params[:page],:per_page => 5)
else
flash[:notice] = "Error"
#posts = Post.paginate(page: params[:page],:per_page => 5)
end
end
Post method for getting data from client side,i have to use def create,i am new to ruby on rails,i dont know to use that data from client side using the post method.
should try this for JSON or XML
def create
respond_to do |format|
#post = Post.new(params[:post])
if #post.save
flash[:notice] = "Prayer Successfully created."
#posts = Post.paginate(page: params[:page],:per_page => 5)
format.xml { render :xml => #post, :status => :created }
format.json{ render :json => #post, :status => :created }
else
flash[:notice] = "Error"
#posts = Post.paginate(page: params[:page],:per_page => 5)
format.xml { render :xml => #post, :status => :created }
format.json{ render :json => #post, :status => :created }
end
end
end
Updated
fetch data (from client end) and create
create an action in your controller
def create_from_app
data_json = JSON.parse request.body.read
#post = Post.new(data_json)
#post.save
end
your android application will hit this action (url something like http://www.exaple.com/create_from_app) with data. This action gonna parse these data and create a post as your expectation.

respond_with - How to respond with a text

I'm using the respond_to and respond_with in a rails app, but in one use case I need to respond with just a text for just one of the resource formats (:json)... But I can't find how to do this...
I want something like this (I know this doesn't work)
def create
...
respond_with(:json, render :text => "Successfully Done!")
end
Any Idea??
Thanks!
It seems that this may be what you are looking for:
def create
respond_to do |format|
format.html
format.json { render :text => "Successfully Done!" }
end
end
Andres,
The solution is this:
class TextController < ApplicationController
respond_to :json, :text
def index
respond_with do |format|
format.json {
render :text => "I'm a text provided by json format"
}
format.text {
render :text => "I'm a text"
}
end
end
end
And at your routes.rb:
match '/text' => 'text#index', defaults: { format: 'text' }

Rails 3: How to "redirect_to" in Ajax call?

The following attempt_login method is called using Ajax after a login form is submitted.
class AccessController < ApplicationController
[...]
def attempt_login
authorized_user = User.authenticate(params[:username], params[:password])
if authorized_user
session[:user_id] = authorized_user.id
session[:username] = authorized_user.username
flash[:notice] = "Hello #{authorized_user.name}."
redirect_to(:controller => 'jobs', :action => 'index')
else
[...]
end
end
end
The problem is that redirect_to doesn't work.
How would you solve this ?
Finally, I just replaced
redirect_to(:controller => 'jobs', :action => 'index')
with this:
render :js => "window.location = '/jobs/index'"
and it works fine!
There is very easy way to keep the flash for the next request. In your controller do something like
flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"
The flash.keep will make sure the flash is kept for the next request.
So when the root_path is rendered, it will show the given flash message. Rails is awesome :)
I think this is slightly nicer:
render js: "window.location.pathname='#{jobs_path}'"
In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:
class AccessController < ApplicationController
...
def attempt_login
...
if authorized_user
if request.xhr?
render :json => {
:location => url_for(:controller => 'jobs', :action => 'index'),
:flash => {:notice => "Hello #{authorized_user.name}."}
}
else
redirect_to(:controller => 'jobs', :action => 'index')
end
else
# Render login screen with 422 error code
render :login, :status => :unprocessable_entity
end
end
end
And simple jQuery example would be:
$.ajax({
...
type: 'json',
success: functon(data) {
data = $.parseJSON(data);
if (data.location) {
window.location.href = data.location;
}
if (data.flash && data.flash.notice) {
// Maybe display flash message, etc.
}
},
error: function() {
// If login fails, sending 422 error code sends you here.
}
})
Combining the best of all answers:
...
if request.xhr?
flash[:notice] = "Hello #{authorized_user.name}."
flash.keep(:notice) # Keep flash notice around for the redirect.
render :js => "window.location = #{jobs_path.to_json}"
else
...
def redirect_to(options = {}, response_status = {})
super(options, response_status)
if request.xhr?
# empty to prevent render duplication exception
self.status = nil
self.response_body = nil
path = location
self.location = nil
render :js => "window.location = #{path.to_json}"
end
end
I didn't want to modify my controller actions so I came up with this hack:
class ApplicationController < ActionController::Base
def redirect_to options = {}, response_status = {}
super
if request.xhr?
self.status = 200
self.response_body = "<html><body><script>window.location.replace('#{location}')</script></body></html>"
end
end
end

Resources