Show data after AJAX call, how to render in controller? - html

I would like to use link_to to call a controller action named show. This happens, I get a 200 message. Now I want to update a div with the content that is being returned.
Code in controller:
respond_to do |format|
format.html # show.html.erb
format.js
end
Code in view, link and JavaScript:
<%= link_to "Show analysis", company_comparison_path(3), :remote => true , :id => "thelink" %>
<div id="replaced"> will be replaced </div>
<script>
$('#thelink').bind('ajax:complete', function() {
$('#replaced').html(data)
});
</script>
I think I still don't understand how to return the HTML or JavaScript from the controller properly into the JavaScript. If I replace the word "data" in the JavaScript with some text in brackets, I get proper output. But how do I get the result from the controller action?

You were almost there, but you need to tell the bound function what the actual html content is you want to insert into your #results div. When you call .html() on $('#replaced') the variable you use (data) is still undefined.
Try the following:
$('#thelink').bind('ajax:complete', function(event, data) {
$('#replaced').html(data.responseText);
});
edit: Oh, something to keep in mind is that this may render your view including the layout which is probably not what you want. You can add something like render layout: false if request.xhr? to your controller to prevent the layout from showing up on ajax requests.

If you want to return richer content from the AJAX response, you can render the view from the controller by the :render_to_string method.
See more: http://apidock.com/rails/ActionController/Base/render_to_string
respond_to do |format|
format.html # show.html.erb
format.js {
#content = render_to_string(:partial => 'some_partial_view')
}
end

Related

Open JSON File in Rails and Stimulus

I have a select form which determines which values are shown in a table. The values are stored in a json file. My Question is: what is the best way to do this cuz i have a gut feeling smth might be wrong with my solution.
Im able to open the json file and save it in a json/jbuilder object in my controller and then call the object in my view and pass the json in the select which calls a stimulus function, which then handles what is shown on the table.
Main Controller:
class MainController < ApplicationController
def index
#itemsJSON = JSON.parse(File.read('db/data.json'))
end
end
Index View
<%= form_with do |form| %>
<%= form.select :city, [['all'], ['critical'],['error'],['warning'],['info'],['debug']],
{ prompt: "Select Item Type" },
data: { controller: "dropdownTable", value: #itemsJSON,
action: "change >dropdownTable#selectData"} %>
<% end %>
Stimulus Function
Code that doesnt work gives back error: localhost:8080/main/db/database.json not found which // i dont understand why
//fetch('/db/data.json')
// .then((response) => response.json())
// .then((json) => console.log(json));
export default class extends Controller {
selectData(event){
... code that works
}
}

Rails controller rendering HTML as plain text, instead of a form

On my site I want a form to be rendered based on what type of data the user is inputing. When I call the controller method in my view, it's outputting tons of HTML where the form should be as plain text starting from DOCTYPE to . I'm using a post form that was previous in place statically to try it out.
Controller:
def feed_form(form_type)
form_type = %w{type_1 type_2}.include?(form_type) ? form_type : 'post'
render "_#{form_type}_form"
end
And the view calling the action:
= feed_form 'post'
And the form:
.feed-form
%h3 News Feed
= form_for(#post) do |f|
= render 'shared/error_messages', object: f.object
.field
= f.text_area :content, placeholder: "Make your new post here..."
= f.submit "Post", class: "post-button"
You are don't supposed to call controller methods from a view.
You must prepare all the data for view rendering (e.g. all required models) in controller method, and put it into #variables.
And then in view you write all your html using already prepared #variables, you can call helpers methods from a view, but not controller's.
Try to put your def feed_form(form_type) code into a helper.
P.S.: and read something about MVC architecture.

Send an http response to another site

Noob
How should I send a single string variable to another site from my rails app? ie the outside service sends a get request to my controller/route and then the controller must respond with the string (and I assume a response code). The string is intended to be added to their html code.
In my controller should I
render :text => "string"
or
respond_with("string) #as xml or json
or something completely different?
Just try the following code. Here your application gives the text and json as per the request.
respond_to do |format|
format.json do
render :json => 'string'
end
format.html do
render :text => 'string'
end
end

Rails routing - how to add .html extension to the routing rule?

I have this rule:
match '*urlnames' => 'home#searching_names'
The URL address looks like website.com/john.html.
The problem is, that in the log I see
Parameters: {"urlnames"=>"john"}
without the .html extension. Text extension is important, I would need to test it in the controller.
I tried to add to the routing rule this part:
match '*urlnames' => 'home#searching_names', :defaults => { :format => "html" }
But still the same, in the log is
Parameters: {"urlnames"=>"john"}
How can I catch the extension in the controller?
You have access to the requested format via request.parameters[:format] or (as a MIME type) via request.format.
However, you can also use a respond_to block:
def show
file = params[:urlnames]
respond_to do |format|
format.html { ... }
format.txt { ... }
end
end
where ... is code to render some text, or send some data or a file.
If you're just trying to show some static files, just place them in the public dir, and bypass Rails entirely.

respond_with redirecting when format=json

I'm encountering a strange behavior in my controllers. They seem to occasionally want to redirect instead of render a json response.
respond_to :json, :html, :js
def create
#favorite = current_user.favorites.build(:location_id=>params[:location_id])
if #favorite.save
respond_with(#favorite)
else
respond_with(#favorite.errors)
end
end
I think it works most of the time but today I was notified of this error:
NoMethodError: undefined method `favorite_url' for #<FavoritesController:0x00000006171dc0>
The params hash was logged as:
{"format"=>"json",
"action"=>"create",
"user_id"=>"56",
"auth_token"=>"iGSty8CMIaWsbShYZEtw",
"location_id"=>"47943",
"controller"=>"favorites"}
Especially strange since it seems to work most of the time... I have changed a few of my other controllers to use the old format.json { render :json => #object } syntax but I'd like to avoid that if possible.
How could this be?
On paths that are not GETs, respond_with tries to redirect to the url for whatever it is given. You can override this with a custom Responder