return JSON in AJAX

387 views
Skip to first unread message

Felipe Pieretti Umpierre

unread,
Jun 14, 2012, 6:45:07 PM6/14/12
to rubyonra...@googlegroups.com
hello guys, I'm trying to make a ajax request and return some data from
my controller, but how I do it to call the JSON in my JS after the
request ?

controller task

def create

@task = Task.create( :project_id => params[ :project_id ], :name =>
params[ :task ] )

if @task.valid?
@return = { :task => @task.name, :project_id => @task.project_id }
else
@return = { :error => "Ocorreu um erro inesperado. Tente
novamente." }
end

return ActiveSupport::JSON.encode( @return )

end

view index - JS

$( "#tasks_form" ).submit( function( e ) {

e.preventDefault();
var task = $( this).find( "textarea" ).val();

$.post( "<%= url_for :controller => :task, :action => :create
%>", { task: task, project_id: <%= @project_id %> }, function( e ) {

}, "json");

} );

Thank you

--
Posted via http://www.ruby-forum.com/.

Max Reznichenko

unread,
Jun 15, 2012, 10:39:07 AM6/15/12
to rubyonra...@googlegroups.com
Try using basic jquery ajax call i.e.

$.ajax({
   url : "your_url"
   // JSON data
}).done(function(response) {
   // here response will have JSON returned by task#create
});

пятница, 15 июня 2012 г., 1:45:07 UTC+3 пользователь Ruby-Forum.com User написал:

Felipe Pieretti Umpierre

unread,
Jun 17, 2012, 2:17:32 PM6/17/12
to rubyonra...@googlegroups.com
Thank you guys for the answer, but I just did this:

render :json => ActiveSupport::JSON.encode( @return )

Linus Pettersson

unread,
Jun 17, 2012, 5:18:13 PM6/17/12
to rubyonra...@googlegroups.com

Max Reznichenko

unread,
Jun 18, 2012, 5:53:49 AM6/18/12
to rubyonra...@googlegroups.com
You can also use respond_with method and change your 
render :json => ActiveSupport::JSON.encode( @return ) 
to
respond_with @return

But for using this, you have to specify responds_to :json in controller

воскресенье, 17 июня 2012 г., 21:17:32 UTC+3 пользователь Ruby-Forum.com User написал:
Reply all
Reply to author
Forward
0 new messages