I have the this link_to in my that calls the update action in my controller:
<%= link_to((image_tag("lock_closed.svg", :class => "edit")), :controller => "sections", :action => "update",:id => section.id, :remote => true) %>
But I would really like to call the update action through some javascript with an ordinary image tag.
So something like:
<%= image_tag("lock_closed.svg", :class => "edit")%>
and:
$(".edit").click(function(){
if ($(this).hasClass("update")){
// call update action
} else {
//do something else
};
})
Is it possible to call an action this way? I've been finding a bit on using GET & POST or Ajax methods but I'm not sure how to utilise them to target a specific controller & action.
Send an Ajax call
$(".edit").click(function(){
if ($(this).hasClass("update")){
$.ajax({
type: "PUT",
url: "/sections/<%= section.id %>"
});
} else {
//do something else
};
})
In order to solve the issue of ActionController::InvalidAuthenticityToken
on the ajax call we should send also the authenticity_token.
$.ajax({
url: '/sections',
data: { authenticity_token: $('[name="csrf-token"]')[0].content,
id: <%= section.id %> },
method: 'POST',
success: function (res) {
....
}
});
Related
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.
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 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/
If I render json in Ruby, how do I access the values in javascript?
In ruby, if I write:
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
How would I access "val" in javascript?
If I do alert(response) in javascript, I see a tag surrounding the json, does this make a difference or is this expected?
I tried jQuery.parseJSON(response) but I got a syntax error. If I try to access response directly, I don't get the correct value- should
response.key === "val"
evaluate to true?
Am I setting it up incorrectly in Ruby or accessing it incorrectly in javascript, or both?
It would really help if you could show your javascript code.
Anyway, one way you can do it is to use jQuery's ajax function and set the dataType to json.
$.ajax({
type: "GET",
url: "<your link>",
dataType: "json",
success: function(response) {
if (response.key)
alert(response.key);
});
});
Hope this helps.
Here's a quick example.
In ./config/routes.rb
match '/index' => 'application#index'
match '/json' => 'application#json'
The controller, ./app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def index
# server side code required by index
end
def json
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
end
end
The erb page an ajax request is made from, in this case ./app/views/application/index.html.erb:
<script type="text/javascript" charset="utf-8">
$(document).ready(
function(){
$("a#my_ajax").bind("ajax:success",
function(evt, data, status, xhr){
console.log(data.key);
console.log(data.key === "val");
}).bind("ajax:error", function(evt, data, status, xhr){
console.log("doh!")
});
});
</script>
<%= link_to "test", {:controller=>"application", :action => 'json'}, :remote=> true, :id => "my_ajax" %>