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
Related
Ok. So I have a small XHR request where json is returned. On success the json is passed like this.
var myArr = JSON.parse(xmlhttp.responseText);
myMainFunction(myArr);
function myMainFunction(arr) {
var vShipTypeID = arr[0].victim.shipTypeID;
}
I need to send vShipTypeID to rails. My goal is to be sending this value back to activerecord and the information returned will go within a js, or json file to the respond_to statement in the controller.
#shipName = InvType.find(vShipTypeID).name
Here's the main idea. The client sends out the ID of the ship to rails, and rails returns the ship's name.
I know how to make the Ajax request.
I don't know how to process the request on the server end. Meaning after rails receives the data, where do I find it, and how to I convert it to be usable so that I can make an activerecord statement out of the value I received from the client?
Anyone?
A simple solution could be defining an action on your ship controller and define a route to it for example define a route in your routes.rb
get "/ship/:id/getname" => "ship#getname"
in your js file
$.get( "/ship/"+vShipID+"/getname")
.done(function(data) {
alert( "Ship name: " + data.name );
})
.fail(function() {
alert( "error" );
});
in you ship_controller.rb
class ship_controller <ApplicationController
....... #other methods
def getname
#shipname = Ship.find(params[:id]).name
if request.xhr
render :json => {name: #shipname} and return
else
redirect_to ship_path(params[:id])
end
end
........ #some other methods
end
You need to handle json requests in your controller check this question for details
for a quick example in your controller create a new action getnamefromid and call that controller from your client.
respond_to do |format|
format.json { render :json => #shipName }
end
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.
I've currently got several partials that contain forms for different AR models. I'm using these to build a dashboard-style pages so I can do an ajax post to CRUD controllers (rather than posting to a bunch of different actions within a dashboard controller).
Since I'm using AR to validate the data, I'd like to be able to just render the correct partial with the correct object in the CRUD controller and use that as my response. Something like this:
if #note.save?
flash[:notice] = "Note successfully saved!"
render '_note_form', :layout => false
else
flash[:notice] = "Something went wrong. Note was not saved!"
flash[:error] = #note.errors.full_messages.to_sentence
render '_note_form', :layout => false
end
Then I'm adding a js function to handle that response by replacing the form with the response like so:
$(function() {
$('form#new_note_form').bind('ajax:success', function(evt, data, status, xhr){
$("#new_note_form").replaceWith(xhr.responseText);
});
});
This gives me validation the same type of validation that I would see if I did a standard post, but only refreshes the partial rather than the entire page.
I can't help but to feel like there is a better way to handle this. Should I just be passing the error/success messages via json and handling them appropriately on the front-end? Is it bad practice to just replace the entire form?
This is my code in my view where I am making an ajax get request to method campaign_creation
$(document).ready(function(){
$("#submit").click(function(){
$.get("/configure_campaign/campaign_creation",{category_name: $("#category_name").val()}, function(data){
$("#category_name").val('');
$("#form_add_category").css("display","none");
alert(data.category_name)
})
})
})
and here is my method code
def campaign_creation
if(params[:page_id] and params[:page_access_token])
abcd=params[:page_id].split("_")
session[:page_id]=abcd[0]
session[:page_access_token] = params[:page_access_token]
else
category=Category.new
category.category_name=params[:category_name]
category.page_id=session[:page_id]
category.save
#category=Category.find(1)
#category.to_json
end
end
I think I should be able to access #category in my variable data. If I simply put data in my alert box I get the complete code of the page and if data.category_name I get the result as undefined.
From the code you've provided for your action alone, you're not going to be rendering a JSON response. Your campaign_creation method is going to try and find a campaign_creation.html.erb file and render a text/html response.
Instead you need to explicitly tell Rails to render JSON data and the end of the action and stop processing.
render json: #category and return
Now you can expect the data variable in your Ajax response to have accesss to the #campaign's :category_name attribute.
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