Handle a JSON response in Rails - ruby-on-rails

I have this code below. I am using an AJAX call and then I need to read a json as a response. In my controller I have this:
def create
# some code
respond_to do |format|
format.html { redirect_to 'index' }
format.json { render :json => {:test =>"test"} }
end
end
How do i read the json response? In which file should I put the javascript code??
$('...').live('ajax:success',function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
I tried in the application.js file but it doesn't work

Related

How do I execute Rails controller logic only in the case of an HTML request?

I have the following line of code, which conditionally redirects that I would like to include in my Rails controller and execute only in the case that the request is an HTML request.
I would like to skip this logic in the case that the request is JSON. How does one do this in conjunction with the respond_to :html, :json method, declared before all controller actions?
redirect_to some_controller and return if #pages.empty?
You want something like this:
class SomeController < ApplicationController
def index
#pages = Pages.find(:all)
respond_to do |format|
format.html do
redirect_to other_controller and return if #pages.empty
# ... other logic ...
end
format.json { render json: #pages }
end
end
end
You should use the respond_to block:
respond_to do |format|
format.html { redirect_to some_controller }
format.json { render json: #data }
end
This will redirect to some_controller after an HTML request, and render JSON data after a JSON request.
You mean just branch logic by HTTP request format.
respond_to do |format|
format.html {your_html_logic }
format.json { your_json_logic }
end

In Rails, how should I update a value in the database with ajax?

When the checkbox is ticked, I just want to update the 'Needed'value in the database.
And the script is list below
$('td div').find('input[type=checkbox]').click(function(){
$.ajax({
type: "PUT",
dataType: "script",
url: '/ecs/2',
contentType: 'application/json',
data: JSON.stringify({ ecs:{needed:'N'}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
});
});
and the controller's code is standard.
# PATCH/PUT /ecs/1
# PATCH/PUT /ecs/1.json
def update
respond_to do |format|
if #ec.update(ec_params)
format.html { redirect_to #ec, notice: 'Ec was successfully updated.' }
format.json { head :no_content }
format.js
else
format.html { render action: 'edit' }
format.json { render json: #ec.errors, status: :unprocessable_entity }
format.js
end
end
end
The EC is the module's name, needed is the column's name. I just want to update a new value in the needed of ec with id=2 .
But right now, I always encountered the BAD REQUEST.
I'm not sure where is the problem.
for your checkbox (make it unobtrusive, it is just a quick example):
... onclick="$.post('/url', {omg_it_is_checked: $(this).attr('checked')})"
in routes.rb:
post '/url' => 'my_controller#my_action'
in controller:
def my_action
#....
#var = some.actions.here.with(params[:omg_it_is_checked]) #or update what you need
respond_to do |format|
format.js{render layout: false}
end
end
than you have to have an appropriate view my_action.js.erb with something like this:
$('#my_uniq_dom_id').html('<%= j render partial: 'new_piece_of_html' %>') #you can render nothing or flash something
and last we need is _new_piece_of_html.html.erb:
<div id="new_ajaxed_content"><%= #var %></div> <!-- or you can render checked checkbox, even with animation, or error message if in some reason it was not saved -->
voila! div#my_uniq_dom_id is updated with div#new_ajaxed_content after controller action
completely different approach - use this gem. it is simple solution for simple needs
cheers!

Rails: Manipulate rendered JSON when using UJS

I enhanced my app by allowing AJAX form submissions, using UJS. Here is my create#product action:
def create
if Product.create params[:product]
respond_to do |format|
message = "New product created."
format.html { redirect_to :back, :notice => message }
format.js { render :json => { :status => true, :message => message } }
end
end
end
But I'm figuring out how to handle outputted JSON in my views/products/create.js.erb file??
I tried this simple console.log example, but without success (I mean, no console output):
$(function(){
console.log(xhr.responseText);
});
Thanks in advance.
You could use:
$('form.new_product').bind('ajax:success',function(event, data, status, xhr){
});
$('form.new_product').bind('ajax:error',function(event, xhr, status, error){
});
or even $('form.new_product').on(same_args).
Just make sure new_product is the actual class of your form.

Rendering json versus js in rails

I'm getting different results if I render js versus render json .Trying to figure out why this doesn't work quite as expected
My javascript looks like this:
$( function () {
$('.delete_post').bind('ajax:success', function () {
$(this).closest('tr').fadeOut();
}
)
});
Controller:
Works
respond_to do |format|
format.js { render :nothing => true}
end
Works
respond_to do |format|
format.js { head :ok }
end
Works
respond_to do |format|
format.json { render :json => {} }
end
Doesn't work
respond_to do |format|
format.json { head :ok }
end
Doesn't work
respond_to do |format|
format.json { render :nothing => true }
end
When I examine what is happening in the ajax response I see that the cases where it doesn't work I get a "parseError".
I understand that the Content-type getting sent back is different (text/javascript vs applicaiton/json), but I would still expect the last 2 cases to work since they are sending back a 200 to the server.
(Code derived from: http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/)
format.json { head :ok }
and
format.json { render :nothing => true }
don't work because they're not returning valid json. head :ok will simply set the response header to 200 and :nothing => true will render a blank page/document which not valid json.

How to make AJAX responses work from the Rails side?

The HTML form:
<form id="newsletter" method="post" action="/subscribers" data-remote="true">
<label for="email">Enter your email:</label>
<input type="text" name="email" class="text" />
<p class="btn"><span>Signup</span></p>
</form>
Note the data-remote="true"
The Controller:
class SubscribersController < ApplicationController
def create
#subscriber = Subscriber.create(:email => params[:email],
:ip_address => request.remote_ip )
respond_to do |format|
format.js
end
end
end
The View (subscribers/create.js.erb)
no clue what goes here to make it return normal AJAX response (or error if it encountered one
1. What do i put in the view to make it return normal ajax response or error? -- Is it even needed to begin with (can I return this without creating such views)
2. Is this the correct way of doing ajax with Rails?
This looks exactly like a question that I just answered today for another user... same model names and everything.
def create
#subscriber = Subscriber.new(#your params)
respond_to do |format|
if #subscriber.save
format.js { render :json => #subscriber, :status => :created, :location => #susbscriber }
else
format.js { render :json => #susbcriber.errors, :status => :unprocessable_entity }
end
end
end
Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.
In the .erb file that contains the form, you would add the following javascript:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#your-form")
.bind("ajax:loading", toggleLoading)
.bind("ajax:complete", toggleLoading)
.bind("ajax:success", function(event, data, status, xhr) {
$("#response").html(data);
});
.bind("ajax:failure", function(event, data, status, xhr) {
//your code
});
});
A standard respond_to block (this allows both html and js) would be:
respond_to do |format|
if #subscriber.save
format.html { redirect_to(#subscriber, :notice => 'Subscriber created.') }
format.js # Not redirecting, just spitting out the JSON(js?) response (I believe).
else
format.html { render :action => "new" }
format.js # Not redirecting for js and this time return error response.
end
end
So what you have actually looks ok to me. Is it working ok or is there an issue?
The above should work with rails2 and rails3. Rails3 has a more succint syntax (of course) but given you are Rails2 I'll leave that for now.

Resources