Rendering JSON in Rails 3.0 - ajax

I'm having trouble rendering JSON with Rails 3.0. Whenever I visit the URL, nothing appears to show up on the screen (I'm pretty sure the JSON should be displaying kind of like XML?) Sorry, I'm fairly new to Rails in general
Here is my code.
def rjson
#comments = Chat.all
respond_to do |format|
format.json { render :json => #comments }
end
end
I simplified it as much as possible. Based on some of the tutorials I have
My routing looks like this:
match '/chatbox/rjson', :to => 'chatbox#rjson'
I'm pretty sure my model is fine.
I don't know if I should even have a 'rjson' view like (rjson.json.erb?) but I'm pretty sure I can just render from the controller without a view right?

If you are sure rjson will only response with json format, you just need:
def rjson
#comments = Chat.all
render :json => #comments
end

Related

Rails - trying to create simple ajax example

The code below is not working for some reason. As I click at "test" it redirects me to /home/test and shows nothing.
view/home/index.html.erb
<%= link_to "test", { :controller => "home", :action => "test" }, :remote => true %>
<div id='test_div'>
</div>
view/home/index.js.erb
$("#test_div").html("some text");
controller
class HomeController < ApplicationController
def test
"test123 test456"
respond_to() do |format|
format.js {render :layout => false}
end
end
end
What should I do to refresh div_test using ajax?
What does your routes file look like? Can you post it on here? Do a rake routes and post the output.
Here are some things that may help you:
Rails documentation for routing
Also, check out the Ajax on Rails Documentation and the section on link_to_remote. The link_to_remote function is not in Rails. What version of rails are you on? Bash: $ rails -v
Look at this answer on S.O. regarding AJAX on Rails calls.
Edit: Here is another answer regarding this that may help.
Another answer on SO for updating existing element
Edit: looking over this again, I dont think you need () after respond_to or the {...} in link_to. Look at the third link. I think you need to put the page in a partial and render it. Its not rendering right now since its render :layout => false

Can't Get Rails 3.1 to respond with js file correctly

I'm trying to make a form in Rails that will respond with a js file. Right now, I have a file in app/assets/javascripts/login.js.coffee.erb that I'd like to be returned when the user submits the form via ajax (I've got users without javascript enabled working fine). Here's my template code for the form:
<%= form_tag("/trade/submit", :method => "post", :remote => true) do %>
# some stuff in here
<% end %>
In my trade controller, I have a method submit, which follows:
def submit
respond_to do |format|
format.html { render :layout => 'widget' + #widget_type.to_s, :template => 'login/index' }
format.js { render :action => 'login', :content_type => 'text/javascript' }
end
end
My respond with html works fine, but when calling the form via ajax, it returns this response:
Missing template trade/submit, application/submit with {:handlers=>[:erb, :builder, :coffee], :formats=>[:js, :html], :locale=>[:en, :en]}. Searched in:
* "~/app_dir/app/views"
Obviously, it shouldn't be looking in views, but rather in javascripts, right? I tried removing the render block after format.js (keeping it default so it will look for submit), and I get the same problem. Does this mean I have to save my js files in my views directory? Seems kinda messy, so I feel like surely I must just be doing something wrong. Any help is greatly appreciated!
It tries to find app/view/trade/submit.js.erb! Try to do a simple test.
touch app/view/trade/submit.js.erb
vim app/view/trade/submit.js.erb
alert('done!');
And run it again.

Alert not working in Rails/ajax situation?

Ch8 of Beginning Rails book has an Ajax forms example which works ok except it does not output an alert for invalid input.
The controller code is:
def create
#comment = #article.comments.new(params[:comment])
if #comment.save
respond_to do |format|
format.html { redirect_to #article, :notice => 'Thanks for your comment' }
format.js
end
else
respond_to do |format|
format.html { redirect_to #article, :alert => 'Unable to add comment due to errors in your input'}
# logger.info("#{Time.now} Ajax invalid validation
##{#comment.errors.full_messages}!")
format.js { render 'fail.js.erb' }
end
end
end
The 'fail_create.js.erb' file contains the one line;
alert("<%= #comment.errors.full_messages.to_sentence %>");
Can some kind person explain why this is not working, thank you
You are rendering "fail.js.erb" but in your question you say the file "fail_create.js.erb" contains the code. Is that a typo in your question or is that the problem in your code?
Also, using RJS is considered bad form in Rails. If you are going through the example as a learning experience more power to you, but it was a failed experiment in the Rails community. Javascript should live on its own (and preferably be added to a site unobtrusively).
Book says to use jQuery 1.4.2
Upgraded to 1.4.4 and all worked well

Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object

I'm trying to add some Ajax functionality in my Rails 3 app.
Specifically, I want a button that will submit an Ajax request to call a remote function in my controller, which subsequently queries an API and returns a JSON object to the page.
Once I receive the JSON object I want to display the contents.
All of this with the new Rails 3 UJS approach, too. Is there a good example/tutorial for this online somewhere? I haven't been able to find one on google. A simple example using a button as the entry point (ie, the user clicks the button to start this process) would work, too.
Edit
Let me try this with a different approach. I want to have this button query an external API, which returns JSON, and display that JSON on the page. I have no idea where to even begin. Does the button itself query the external API? Do I need to go through the controller, and have the controller query the external API, get the JSON, and give the JSON back to this page? How do I display/access the contents of this JSON? I honestly can't find a good Rails 3.x example of how to handle JSON...
Here is a start:
First create your button with a link_to method in your view, for example:
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
Note that I am appending ".json" to the url of my resource. This is just an example of a an AJAX delete, google link_to to see the meaning of the parameters. The concept if that you make your HTTP request with the parameter :remote set to true, in other words this is translated to an AJAX call from your browser.
Second, write some javascript so that you can process what ever is the result of the AJAX call your browser will make when the user click on the link_to of step 1. For details you can see this blog post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
An example from my site:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#pending_invitation")
.live("ajax:loading", toggleLoading)
.live("ajax:complete", toggleLoading)
.live("ajax:success", function(event, data, status, xhr) {
var response = JSON.parse(xhr.responseText)
if (response.result == "ok") {
$(this).fadeOut('fast');
}
else {
var errors = $('<div id="error_explanation"/>');
errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
$('#new_invitation_error').append(errors)
}
});
});
where you can see that I parse the returned json and and change the html on the page based on that. Note that this js uses the CCS ids and classes defined in the top view that is not included here.
If you now want to write you own controller to spit out the json here is an example:
class InvitationsController < ApplicationController
respond_to :html, :json
# other methods here
# ...
def destroy
#invitation = Invitation.find(params[:id])
respond_to do |format|
if #invitation
#invitation.destroy
flash[:success] = I18n.t 'invitations.destroy.success'
format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
else
format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
end
end
end
end
Hope this help.
Old question, but a really good overview of Ajaxifying Rails applications is:
Ajax in Rails 3.1 - A Roadmap
Also consider returning errors in the following format:
render :json => #myobject.to_json, :status => :unprocessable_entity
This will ensure that your client can process the response as an error.

Ruby w/ Sinatra: Could I have an example of a jQuery AJAX request?

%a{:href => "/new_game?human_is_first=true", :remote => "true"}
%span Yes
Above is my link. Just wondering how to handle this. I need to be able to execute some javascript. Below is a .js.erb file from back when I using rails.
$('.welcome_container').fadeOut(500, function(){
$( '.shell' ).html( "<%= escape_javascript( render( :partial => "board/board" ) ) %>" );
$('.board_container').fadeIn(500);
});
So, my question is, Once /new_game is called in app.rb, I want to be able to send some javascript to the current page (without leaving the page, and have the partial rendered)
See my answer to your other recent question for a comprehensive setup for sending and receiving HTML partials in a production Sinatra app.
As Sinatra is a nice lightweight framework, you are free (forced?) to come up with your own workflow and code for implementing partials and handling such calls. Instead of my explicit route-per-partial, you might choose to define a single regex-based route that looks up the correct data based on the URL or param passed.
In general, if you want Sinatra to respond to a path, you need to add a route. So:
get "/new_game" do
# This block should return a string, either directly,
# by calling haml(:foo), erb(:foo), or such to render a template,
# or perhaps by calling ...to_json on some object.
end
If you want to return a partial without a layout and you're using a view, be sure to pass layout:false as an option to the helper. For example:
get "/new_game" do
# Will render views/new_game.erb to a string
erb :new_game, :layout => false
end
If you want to return a JSON response, you should set the appropriate header data:
get "/new_game" do
content_type :json
{ :foo => "bar" }.to_json
end
If you really want to return raw JavaScript code from your handler and then execute that...well, here's how you return the JS:
get "/new_game" do
content_type 'text/javascript'
# Turns views/new_game.erb into a string
erb :new_game, :layout => false
end
It's up to you to receive the JS and *shudder* eval() it.

Resources