Rendering js.erb output raw javascript code - javascript

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.

Related

How to access Rails model attributes inside JavScript?

<%= form_for(#mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
<!-- I need to check if #mymodel.match_id matches the value generated by a controller function -->
<%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>
<script type='text/javascript'>
$(function() {
$(document).on("click", "#match_submit", function(event){
$.ajax('my_controller_method', {
type: 'GET',
dataType: 'script',
data: {
mid: $("#").val(), // how do I pass #mymodel.match_id here?
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
</script>
I have a Rails form that represents a model as shown above.
How can I access attributes of the model inside the JavaScript code block shown above?
You can use erb inside of javascript too:
mid: <%= #mymodel.match_id %>,
Or you can serialize your object with gon gem (https://github.com/gazay/gon)

How to respond with format.pdf in rails 5

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.

form_tag onComplete event not work

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>

How to access an instance variable inside JavaScript?

I have the following controller actions:
def new
#tag = Tag.new({company_id: current_member.company_id })
end
def create
#tag = Tag.new(tag_params)
#companyid = current_member.company_id
respond_to do |format|
if #tag.save
format.html {redirect_to root_path}
format.json {render :json=> #tag}
else
format.html {redirect_to root_path}
end
end
end
Inside my new.html.slim view file I have:
= simple_form_for #tag, url: tags_new_path, html: {id:'tag_form_submit', method: :post}, format: :js, remote:true do |t|
=t.input :name, placeholder: 'tag'
=t.button :submit, "submit tag", id:"submit_tag_button"
javascript:
$(document).ready(function(){
$("#submit_tag_button").click(function(event){
event.preventDefault();
<!-- $("#tag_form_submit").hide(); -->
<!-- $('#add_tag_tag').hide(); -->
var text = $("#inputbox").val();
var name = $("#tag_name").val();
var datatosend = { tag: {name:name, company_id: "#{#companyid}" } };
$.ajax({
url: "/tags/new",
dataType: "json",
method: "post",
data: datatosend,
success: function(result){
console.log(result)
var nameVar=result.name;
var idVar=result.id;
console.log(nameVar);
console.log(idVar);
var newspan='<span class="checkbox"><label for="job_tag_ids_'+idVar+'" name="job[tag_ids]"><input class="check_boxes optional form-control" data-remote="true" id="job_tag_ids_'+idVar+'" name="job[tag_ids][]" type="checkbox" value="'+idVar+'">' + nameVar + '</label></span>';
$("#all_tags > div.form-group.check_boxes.optional.job_tags > div").append(newspan);
<!-- $(#event_tag_ids).append('hi'); -->
if ($("#event_tag_ids").length){
$("#event_tag_ids").append('<option value="'+idVar+'">'+nameVar+'</option>');
}
// after its appended, erase from form input
console.log(result.company_id);
$("#tag_name").val("");
}
})
})
});
In my datatosend varible I am trying to send:
var datatosend = { tag: {name:name, company_id: "#{#companyid}" } };
but #companyid is being posted as null. Why?
How do I successfully access #companyid from the controller inside my JavaScript so I can send it in when making my AJAX post call?
You're only assigning the #companyid instance variable in the create action of your controller, not the new action.
The view template you posted is rendered as part of the new action. So you should change your controller:
def new
#companyid = current_member.company_id
#tag = Tag.new(company_id: #companyid)
end

Calling Rails action from Javascript

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) {
....
}
});

Categories

Resources