Im trying to use jquery to get a controller action which shows a pdf page. Before the javascript way, the rails way worked:
Show.html.erb
<%= link_to "Get PDF", client_path(#client.id, format: :pdf) %>
The issue is, I need some params that I get from javascript so a work around was to use ajax to make the request:
js:
$.ajax({
url: "/clients/" + clientId + ".pdf",
type: 'POST', // Ive also tried GET and created a post route in routes.rb
data: { //...
},
success: function(data, xhr) {
//...
console.log('Success.....');
},
error: function() {
console.log("Error....")
}
});
Controller:
respond_to :html, :xml, :json
def show
respond_with do |format|
format.pdf do
render pdf: "demopdf",
template: "clients/show.pdf.html.erb",
locals: {:client => #client}
end
end
end
If I click my rails button, I get the pdf view but not so with a normal button with a button click function. How to do this with ajax? I got the success log but that's it.
EDIT:
How to get Bar to my controller? I need to have Bar in my pdf?
show.html.erb:
<p id="foo"></p>
js:
$("#foo").text("Bar");
So basically I need to pass few params in:
<%= link_to "Get PDF", client_path(#client.id, format: :pdf) %>
If you need to send the parameters, you can do so by adding params in your route code.
<%= link_to "Get PDF", client_path(#client.id, format: :pdf, params1: 'some param', params2: 'other param2' ...) %>
If you need to use the ajax for the link, the add
remote: true in there as well.
Related
I have an ajax post to my backend rails app, it's to post a upload a file.
Post response with my files list in JSON
After that I need to reload my files list at view detalhes.html.erb page. This list is a partial. Here is what I have:
controller method:
def upload_arquivo
#ponto_venda = PontoVenda.find(params[:pv_id])
nome = params[:key].split('/').last
#arquivo = Arquivo.new(nome: nome, endereco: params[:url], s3_key: params[:key], tamanho: params[:tam], user_id: params[:u_id], tag_id: params[:tag])
if #arquivo.save!
ArquivoPontoVenda.create(arquivo_id: #arquivo.id, ponto_venda_id: #ponto_venda.id, fachada: false)
response = { files: filtro_pv_arquivos, message: "O arquivo '#{nome}' foi salvo" }
else
response = { files: '', message: 'Ocorreu um erro ao salvar o arquivo, por favor, tente novamente' }
end
render json: response
end
My ajax post method at _arquivos_upload.html.erb:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
console.log(data.files.length);
// trying to reload partial after post request
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados") %>");
});
data.files are correct, I just need to find a way to pass this to my render partial. How can I do that? Or if this is a bad way to do it, how can I do better?
Here is where I render my partial detalhes.html.erb:
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados" %>
</div>
I already have try a lot of this:
github link
set .html(data.files)
use js.erb file logic
That looks good. I'd suggest modifying your partial to accept a local variable and then explicitly passing it in when you render the partial.
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados", locals { files: #files #add this } %>
</div>
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados", locals: { files : data.files } ) %>");
I think I would render back html instead of json. Then, in .success function of the ajax call, just do:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
$('#display-arquivos').html(data);
});
You'll probably need to change your controller action along the lines of:
def upload_arquivo
...
if #arquivo.save!
ArquivoPontoVenda.create(arquivo_id: #arquivo.id, ponto_venda_id: #ponto_venda.id, fachada: false)
#files = #populate your #files variable
render "arquivos_buscados"
else
render :something_else
end
end
I am doing this simple ajax call in my rails app like this.
<%= link_to 'test_js', '#', class: "ajax_call" %>
<script type="text/javascript">
$(".ajax_call").on("click", function () {
$.ajax({
url: "<%= users_get_details_path %>",
dataType: 'script',
type: 'GET'
});
})
</script>
and my controller action looks like this
def get_details
respond_to do |format|
format.js {}
end
end
get_details.js.erb
$(document).ready(function () {
console.log('working!!!');
alert("working!!!");
});
This does not give any alert or text in the console or any error instead it outputs the whole js.erb raw content in the dom console. I don't understand what I am doing wrong here.
If you want get console log or alert when finish ajax request, you can do like below:
<%= link_to 'test_js', '#', class: "ajax_call" %>
<script type="text/javascript">
$(".ajax_call").on("click", function () {
$.ajax({
url: "<%= users_get_details_path %>",
dataType: 'script',
type: 'GET',
success: function(data){
console.log('working!!!');
alert("working!!!");
console.log(data);
}
});
})
</script>
I add console.log(data) to log what data you got from users_get_details_path.
Hope it helps.
I want to call a javascript function when click the submit button.I used form_tag , but the function did not get triggered.I want something like the following:
<%= form_tag show_table_job_plate_path, :onSubmit => 'start_form_request(); ' ,:onComplete => 'end_form_request();' ,:update => { :success => 'well_table_section' },:remote => true, method: :GET do %>
on submit is working but on complete is not working please help me?
There is no onComplete event on HTML Form. Check this
If you want to trigger something after on Ajax Call Complete. Use Ajax events like success, complete, error.
$("#yourform").bind('ajax:complete', function(data, status, xhr) {
//Your On Complete Code
});
Check this for all rails ajax events.
As you are using form_tag with remote:true, which means your rails server is going to send you response in JS format. So you can call your function with following two ways:
1) respond_to block: simplest and easy solution.
respond_to do |format|
format.js { render :js => "end_form_request();" }
end
2) js.erb file:
for your controller action you can have "action_name.js.erb" file, and in that file you can call you js function 'end_form_request()' directly.
Hope it helps you.
Updated:
action.js.erb
$("#well_table_section").html("<%= escape_javascript(render partial: 'well_table', :locals => { :params => #params } ) %>");
end_form_request("<%= #params %>");
You can try this
$("#your_form_id").on("ajax:success", function(xhr,data){
... //your complete function here.
})
As per your request I converted your requirement into Rails 4
This is form tag
<%= form_tag show_table_job_plate_path, remote: true, html: { onSubmit: 'start_form_request();', id: 'yourForm' } do %>
When you added the show_table_job_plate_path in the form you don't need to method: :GET
After the form you have to add this script.
<script>
$(document).ready(function(){
$('#yourForm').on('ajax:complete', function(e, data, status, xhr){
// Write onComplete Code
end_form_request();
}).on('ajax:success',function(e, xhr, status, error){
// Write onSuccess Code
well_table_section();
}).on('ajax:error',function(e, xhr, status, error){
// Write onError Code
});
});
</script>
I have a Cart controller and a "show" view which shows the contents of the cart. I want to show the cart in every view of my Products controller. So, I'm rendering the cart/show in products/show using
<%= render "/cart/show" %>
Now, I want to update the cart via ajax when a user wants to add a product. Please guide me how I should design my controllers to achieve this.
How to use partials to DRY up your views.
http://guides.rubyonrails.org/layouts_and_rendering.html
function postToRailsApi() {
$.ajax({
type: "POST",
url: "the_url_you_want_to_post_to/endpoint",
data: {someData: {thisId: otherId}},
dataType: "json",
success: function(data) {
alert("OMG SUCCESS status:200")
}
});
In the rails controller:
respond_to do |format|
if #my_condition.save
format.html {render nothing: true, status:200}
format.js{render nothing: true, status:200}
format.json { render json: #timestamp, status: 200 }
else
format.html { render action: "new" }
format.js { render nothing: true, status: 400 }
format.json { render nothing: true, status: 400 }
end
end
Obviously your logic will be different.
I have a semantic_form_for in my view that sets up a search filter, and more filters are added with a button that, through JavaScript, adds more filters.
<%= semantic_form_for current_coach, :remote => true, :html => { :class => "custom-form rb-form", :id => "filter", :'data-url' => "#{roster_builder_coach_index_path}" } do |f| %>
<div class="filter_parent_container">
<% #search.conditions.each do |condition| %>
<%= render "filter", :condition => condition %>
<% end %>
</div>
<div class="bottom-info">
<div class="count">
<p class="num"><%= #athletes.count %></p>
<p>identified with this filter set</p>
</div>
<input type="submit" class="send-request" id="search-button" value="" />
<input type="button" class="add_filter" value="Add Another Filter" />
</div>
<div class="cl"> </div>
<% end %>
I need the form to submit via ajax, but it isn't. I'm checking the params in the controller and they are:
{"action"=>"roster_builder", "controller"=>"coach"}
Here's the controller (logger is checking the params):
def roster_builder
authorize! :access_roster_builder, current_coach
logger.info("**************");
logger.info("**************");
logger.info("**************");
logger.info("**************");
logger.info("**************");
logger.info(params);
#search = Search.new(sport: current_coach.primary_sport, conditions: params[:search])
#athletes = #search.query.page(params[:page]).per_page(8)
render "athletes" if request.format.js?
end
Here is the Ajax call:
$("#filter").submit(function(){
$.ajax({
url: $("#filter").attr("data-url"),
type: 'POST',
success: function(data) {
$(".results")[0].parentNode.removeChild($(".results")[0]);
}
});
});
Before I used :remote => true, it was working, but I need persistence across the filters (including the ones added via JS), so I need Ajax to perform the search rather than doing a page refresh. Why isn't params working now that Ajax is sending the form data? I even tried sending the data via Ajax as serialized, to no avail, as follows:
$.ajax({
url: $("#filter").attr("data-url"),
type: 'POST',
data: $("form#filter").serialize(),
success: function(data) {
$(".results")[0].parentNode.removeChild($(".results")[0]);
}
});
Any help would be appreciated!
Do not use both remote: true AND an ajax call in the submit event of the form.
If you make the ajax call yourself, then you will definitely need to pass the params with data: $("form").serialize()
You have to return false, or do e.preventDefault() in the submit event, because you don't actually want the form to be submitted, since you're sending the data yourself with the ajax call.
this plugin to handle ajax forms is great: http://www.malsup.com/jquery/form/