How to pull a record with AJAX - ruby-on-rails

On my site I have a simple model called Feed.
I want to make a link/button that will pull the Feed record with id=5 (for example) using AJAX.
The record that has been pulled should be displayed in a partial.
How can I do that ?
Thanks,
Oded

If you use jQuery, you could do sth like this:
In your controller you must respond to ajax request using the respond_to :js. Then you could either render directyl javascript which will be executed on your site, or the way I suggest you, to render json and parse it on the client side.
class YourController < ApplicationController
def index
#model = YourModel.all
respond_to do |format|
format.html
format.json {
render :json => #model.to_json
}
end
end
On the client side, just bind a click handler and then fetch the data using the path to your controller:
$("#your_link_id").click(function() {
$.getJSON('/path_to_your_controller', function(data) {
console.log(data);
});
}
The code is not tested, but it should work in that way.
Note: the console.log works with firefox but not with safari, try using firebug for console output.

Kind of long for a SO answer, but this should get you going:
http://www.tutorialspoint.com/ruby-on-rails-2.1/rails-and-ajax.htm
That's where I got started with AJAX on RAILS

Related

how to send two models includes data to ajax success call

I have two models called User and post. now am calling controller action through ajax. Now i want to send User.includes(:posts) data to ajax success function. Am successfully sending data also. But in ajax success function am able to see only users data but not posts data.
$.each(data,function(k,v) {
$('#testDataTable tbody').append('<tr><td>'+v.id+'</td><td>'+v.name+'</td></tr>');
});
Am trying v.posts but its saying undfined . How to achieve this. Thanks in advance.
In Controller My code is
#e = Master.find(params[:id])
#data = #e.users.includes(:posts)
respond_to do |format|
format.json { render :json => #data}
end
Just using includes on your association will not load the association data in the json.
You will have to do
#e.users.as_json(include: :posts)
This will render the posts in the json data

How to ask two queries from a single controller

I am trying to do everything on a single page. The page is called users/index.html.erb.
On this page I return a simple data base query in json format.
I would like to also return a seperate query in non json format from the same database.
I'm trying to avoid partials for the moment as they make variable handling a bit more complicated that I want for my beginner level.
This is what I have:
class UsersController < ApplicationController
def index
#users = User.including_relationships
#followas= User.find_by name: params[:name]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
end
but it doesnt work unsurprisingly. How can I get it to work in one action?
Not sure about your purpose of returning two formats of query from a single controller call. It usually happens when you use Javascript heavily (eg. Angular.js). Controller first returns the HTML page including all the HTML template and javascript, then data in JSON is returned in the second round.
So in your users/index.html.erb, you might have something like:
<p ng-repeat='user in users'>{{user.name}}</p>
<script>
// do a AJAX call to retrieve users in JSON format
</script>
Then you will call users/index.json again to retrieve users information in JSON.
In short, your users/index is called twice, once for html, once for JSON.
It might seem unwise to call the same controller method twice just to render different format. In such case, you might consider to embed the JSON data in HTML. In such way, you will only render users/index.html.erb once and parse the data in JSON through Javascript on the client side.

Error in handling reponse from remote true Rails

I am using Rails remote true for ajax calls, but I have error in handling the response form controller.
What I am doing is I have placed a form in partial which I render in the view for the first time, and I have also given it a id in html options for form_for. I have also applied some jQuery on that form like on save and cancel button and one script for date picker on one of its field.
As I handle the response from server using format.js for rendering js file, in which I have placed the code as follows
if #vairable.save
format.js { render 'some-file' }
else
format.js { render 'something'}
end
If the variable saved successfully I close the form properly, but if validations occur I render the form again by writing JavaScript code in js.erb file. I have problem in handing this response. The errors are displaying properly but when the form renders again with errors, the jQuery events applied to its fields and button, do not work. The jQuery events don't take place.
This problem only occurs when the model validations occurs and the validation rails are displayed with the new render form.
You should wrap your response in a respond_to block like this:
respond_to do |format|
if #variable.save
format.js { render 'some-file' }
else
format.js { render 'something'}
end
end
Edit: Your jQuery tags should be changed to $(document).on(...). Eg.
#change this:
$("#your-target-id").click(function(){
alert("This doesn't work after your have submitted via ajax")
});
#to this:
$(document).on("click", "#your-target-id", function() {
alert("This should work after ajax submission, and when errors are displayed");
});

Having to call "render :layout => false" to correctly render js.erb template in Rails 2.3.3

I'm running the latest Rails 2-3-stable branch (currently 2.3.3).
I'm using JQuery to post an AJAX request to my 'create' action, in which I have the following block:
respond_to do |format|
format.js
end
I have created create.js.erb and to test this action, I've added the following single line:
alert('hello');
The request correctly enters the format.js block, but the response attempts to render a layout. Here's my log:
Jul 22 20:44:27 [2970] INFO: Rendering template within layouts/application
Jul 22 20:44:27 [2970] INFO: Rendering contacts/create
If I change my respond_to block to the following, it works:
respond_to do |format|
format.js { render :layout => false }
end
Is this expected behaviour or is this a bug in Rails? I would have thought the fact that I'm rendering a JS response would be enough to set layout to false.
I use this:
class ApplicationController < ActionController::Base
# this is needed to prevent XHR request form using layouts
before_filter proc { |controller| (controller.action_has_layout = false) if controller.request.xhr? }
It works like charm. You have to put this onliner only in one place and noting more.
I have spend ~1 h to write this line.
The best way I've found to handle this is to add a file like this:
app/views/layouts/application.js.erb
<%= yield -%>
If you don't include the yield, your js actions will all fail, since the app will never render the view. This technique solves the layout problem and also offers the ability to add universal js code at the layout level, such as flash processing or triggering jQuery UI onLoad hooks.
My memory of Ajax on Rails books is that this was the standard if not necessarily expected behaviour in earlier editions of rails.
The following ticket shows the bug logged a few versions back, as well as a way to define the behaviour as default.
http://dev.rubyonrails.org/ticket/3229
Sadly the description of what the later changes are that make this obsolete are not explained in the final comment.
The JQuery function which makes the Ajax POST request should return "false". Check if you are doing the same. It should be implemented like following:
postFormData: function () {
$('#form_id').submit(function () {
$.post($(this).attr('action'), $(this).serialize(), null, 'script');
return false;
});
}
Notice the last line which returns false.

When does "respond_to do |format|" make sense for Javascript?

I saw this code in a Rails controller:
respond_to do |format|
format.js {}
end
I've seen this for XML and HTML formats but not for Javascript.
Is this the way you specify a return format if you use for REST, like if you use replace_html or remote_form_for? I know RJS templates return compiled Javascript so I'm thinking maybe this is where this code might kick in.
If you put code inside the hash symbols(format.js {}), is that what gets send back as javascript to the browser?
It is used when an AJAX request is sent from the browser to a controller. The controller can respond with a script (which is generated by ruby statements in the view) which will be executed on the client.
Rails does a little magic on figuring out what 'template' to send out
in controller:
def foo
end
in view: (app/views/controller/) you can have
foo.html.erb (usual, html template)
foo.rjs (javascript template)
rails will send out the right template back to the browser, HTML for regular requets and RSJ for Ajax requests. You might want to put in javascript code like 'page.replace_html' ..etc in your RJS template. This way, you keep the controller clear of view code.
yuo can always just add the format to the url and see what it responds, /something.js would respond using the format.js code, if you want to use it, you can do the following to avoid rendering your entire layout:
format.js { render :layout => false, :text => #models.to_json }
that would respond with a json string
format.js { render :layout => false }
would require a template called [action].js.erb

Resources