How set form aciton to javascript:; on ruby on rails - javascript

I Request Form action using javascript.
But Page occured Error
undefined method `chomp' for nil:NilClass
<%= form_for message , url: "javascript:;" do |f| %>
<%= f.text_field :content, class: "form-control", data: { textarea: "message" } %>
<%= f.submit "Send", class: "btn btn-primary", data: { send: "message" } %>
<% end %>
I thinks url: "javascript;;" occured this error.
How to fixed these code?

If you want ajax call so use remote:true
<%= form_for message , remote: true do |f| %>
<%= f.text_field :content, class: "form-control", data: { textarea: "message" } %>
<%= f.submit "Send", class: "btn btn-primary", data: { send: "message" } %>
<% end %>

Related

Send email using html button javascript and Rails

Im new to using rails and i have a test where im given a code that send an email through a click and i have to compleate it,
Here is the code:
app/views/root/index.html.erb
<%= form_tag root_path, class: "send-email" do %>
<%= submit_tag "Click to Send Email", style: "margin: 10px; padding: 10px" %>
<% end %>
<script>
document.querySelector(".send-email").onsubmit = function(e) {
e.preventDefault()
fetch(e.target.action, {
method: "POST",
headers: {
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
}
}).then(function(response) {
if (response.ok) {
window.open('/mail', '_blank')
} else {
console.error(response)
}
});
}
</script>
How can i fix this to be able to send an email when clicking ?

Ajax event not triggered

I'm trying to trigger an AJAX event when both arrival and departure date are filled in, but unfortunately nothing is triggered. Without the if statement, the AJAX event is triggered.
Any thoughts?
reservations/new.html.erb
<%= simple_form_for [#hotel, #reservation] do |f|%>
<div class="col col-sm-3">
<%= f.input :arrival,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "start_date"} %>
</div>
<div class="col col-sm-3">
<%= f.input :departure,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "end_date"} %>
</div>
<div class="col col-sm-4">
<%= f.input :room_id, collection: #room_categories.order(:name), as: :grouped_select, group_method: :rooms, label:false %>
</div>
<%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>
script for reservations/new.html.erb
<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
// => if statement that doesn't work
if ((checkIn.value.length > 0) && (checkOut.value.length > 0)){
const checkInAndOut = [checkIn, checkOut];
checkInAndOut.forEach((item) => {
item.addEventListener('change', (event) => {
checkAvailability();
})
})
//}
function checkAvailability(){
$.ajax({
url: "<%= rooms_availability_hotel_path(#hotel) %>" ,
dataType: 'json',
type: "POST",
data: `arrival=${start_date.value}&departure=${end_date.value}`,
success: function(data) {
console.log('succes')
console.log(data);
},
error: function(response) {
console.log('failure')
console.log(response);
}
});
};
</script>
You need to move your length check
if ((checkIn.value.length > 0) && (checkOut.value.length > 0)){
into the listener function.
Because otherwise it is only called on page load and therefore is stopping the attachment of the listeners.

Rails js.erb not rendering partial file but get response file rendered

I have the following partial files
_report.html.erb
<h5>REPORT</h5>
<hr/>
<%= link_to "Extract REPORT", "#", :class => 'btn btn-primary', id: 'load_panel' %>
<br/>
<br/>
<div class="row">
<% rand = Time.now.to_i - Random.new.rand(1..Time.now.to_i) %>
<div class="col-md-12">
<input type="hidden" id="randValue" value="<%= rand %>" data-validate="false" data-hidden="true"/>
<div>
<b>File Name</b>
<hr/>
</div>
<div id="application-attachments-<%= rand %>" class="col-xs-12">
<%= render partial: 'report_attachment', locals: {application_attachments: f.object.application_attachments} %>
</div>
</div>
</div>
_report_attachment.html.erb
<% application_attachments.each do |attachment| %>
<div class="fields">
<%= render "report_attachment_fields", rep_attachment: attachment, instalment: true, type: 'application_assignment' %>
</div>
<% end %>
_report_attachment_fields.html.erb
<div class="row attachment_display">
<% if rep_attachment.attachment? && rep_attachment.attachment.model.share_file %>
<% if #action == "show" && #account_type %>
<div class="col-md-6 ellipis">
<%= link_to File.basename(rep_attachment.attachment.path), rep.attachment.url, target: "_blank", id: 'view_file', :data => { application_attachment_id: rep_attachment.id } %>
<%= rep_attachment.active %>
</div>
<% end %>
<% end %>
</div>
Upon initial load, it loads all 3 files accordingly. But Upon clicking Extract CTOS, it makes a javascript request
application.js
$('body').on('click', '#load_panel', function(event) {
object_selected = $(this)
$(this).attr('disabled', 'disabled');
$.ajax({
type: 'GET',
url: '/applications/generate_report?application_id='+$(this).attr('data-application-id')+'&rand_value='+$(this).attr('data-rand-value'),
dataType: 'json',
success: function(data) {
object_selected.removeAttr('disabled');
}
})
})
On calling the GET request, it will call this method
def generate_report
#rand_value = params[:rand_value]
#rep_application_attachment = #application.rep_attachment
respond_to do |format|
format.js
end
end
Which should call this js.erb file
generate_report.js.erb
$("#application-attachments-#{#rand_value}").html("<%= escape_javascript(render 'report_attachment', application_attachments: #rep_application_attachment) %>");
The problem now is that i dont get an error and it says generate_report.js.erb has been rendered but it doesnt render anything. What am i missing?
solved it. It had to do with my ajax call.
$.ajax({
type: 'GET',
url: '/applications/generate_report?application_id='+$(this).attr('data-application-id')+'&rand_value='+$(this).attr('data-rand-value'),
dataType: 'json',
success: function(data) {
object_selected.removeAttr('disabled');
}
})
should be this instead. by not including datatype ='script' and correct format, even though my js.erb got called, it wasn't executed.
$.ajax({
type: 'GET',
url: '/applications/generate_report?application_id='+$(this).attr('data-application-id')+'&rand_value='+$(this).attr('data-rand-value'),
data: {
format: 'js'
},
dataType: 'script',
success: function(data) {
object_selected.removeAttr('disabled');
}
})
You need to specify 'partial' option to render template using render method.
Try this
generate_report.js.erb
$("#application-attachments-#{#rand_value}").html("<%= escape_javascript(render partial: 'report_attachment', application_attachments: #rep_application_attachment) %>");
your original code:
$("#application-attachments-#{#rand_value}").html("<%= escape_javascript(render 'report_attachment', application_attachments: #rep_application_attachment) %>");
Rendering partials
Partial rendering in a controller is most commonly used together with Ajax calls that only update one or a few elements on a page without reloading. Rendering of partials from the controller makes it possible to use the same partial template in both the full-page rendering (by calling it from within the template) and when sub-page updates happen (from the controller action responding to Ajax calls). By default, the current layout is not used.
For more information about render
https://apidock.com/rails/ActionController/Base/render
I think the problem is that you're trying to interpolate your ruby instance variable the wrong way (you're using Ruby's string interpolation syntax "#{}"), when you need to use ERB "<%= %>".
This should work:
$("#application-attachments-<%= #rand_value %>").html("<%= escape_javascript(render 'report_attachment', application_attachments: #rep_application_attachment) %>");

How to execute Javascript after Rails' remote form `disable_with` functionality has completed?

I am using disable_with, and cannot get the button text change to persist (because it is being overwritten by the disable_with functionality). As soon as I remove , data: { disable_with: '...' the buttons are updated as expected.
Is there a way to perform actions after the disable_with functionality has completed?
form:
<%= form_for #user, html: {id: 'follow-form'}, remote: true do |f| %>
<%= button_tag id: 'follow-btn', data: { disable_with: '...' } do %>
Follow
<% end %>
<% end %>
js:
$('#follow-form').on('ajax:success',function(data, status, xhr){
if (status.action == 'follow') {
$('#follow-btn').text('Unfollow');
} else {
$('#follow-btn').text('Follow');
}
}
Maybe without disable_with and:
$('#follow-form').on('ajax:send',function(data, status, xhr){
$('#follow-btn').text('Please wait...').attr({disabled: true});
});
And when AJAX request succeeds:
$('#follow-form').on('ajax:success',function(data, status, xhr){
if (status.action == 'follow') {
$('#follow-btn').text('Unfollow').attr({disabled: false});
} else {
$('#follow-btn').text('Follow').attr({disabled: false});
}
});

Passing JavaScript variable to ruby-on-rails controller

How can I pass a variable (id) from the JavaScript listener:
Gmaps.map.callback = function() {
...
...
google.maps.event.addListener(marker, 'click', function() {
var id = this.currentMarker;
alert(id);
});
}
}
To the instance variable (#foo) in ruby-on-rails controller
def create
#foo = ???
...
end
to correctly create a relationship in the view (form):
<%= form_for user.relationships.build(:followed_id => #foo.id) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<div class="actions"><%= f.submit "Follow" %></div>
<% end %>
Thanks!
If I am understanding correctly, a good way to do this is to use AJAX to submit the id to your action and use the action to render your form.
That would look something like this in your javascript:
jQuery.ajax({
data: 'id=' + id,
dataType: 'script',
type: 'post',
url: "/controller/action"
});
You'll need a route:
post 'controller/action/:id' => 'controller#action'
Then in your action you can grab that id and render your form something like this:
def action
#user = User.relationships.build(:followed_id => params[:id])
render :viewname, :layout => false
end
Then you can just build a form for #user in a partial or whatever
<%= form_for #user do |f| %>
You'll have to fill in the details there, but that should get you pretty close.

Categories