Send email using html button javascript and Rails - javascript

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 ?

Related

How to make a file loading progress bar for the rails form?

I'm trying to make a form that has an title, email, content and file upload fields. When the user click submit the uploaded file is saved in the database and the link with the location and hashed name is send to admin. That all works but the files that users are gonna upload are big and I would like to have some loading bar. I know there are many similar questions on stackoverflow but I was not able to make it work.
First I set two routes:
get "message", to: "messages#index"
post "message_create", to: "messages#create"
Over the first I get the form:
<%= form_tag(message_create_path, :method=>'post', class: "section form", :multipart => true) do %>
<fieldset class="form__fieldset">
<div class="form__field">
<%= text_field_tag 'name', nil, class: 'input', placeholder: 'Name', id: 'name' %>
</div>
<div class="form__field">
<%= text_field_tag 'email', nil, class: 'input', placeholder: 'Email', id: 'email' %>
</div>
<div class="form__field">
<%= text_area_tag 'content', nil, class: 'input textarea', rows: '10', placeholder: 'content', id: 'content' %>
</div>
<div class="form__field">
<%= file_field_tag 'file', id: 'input_file' %>
</div>
<div class="progress">
<div class="bar"></div >
<div class="js-percent">0%</div >
</div>
</fieldset>
<fieldset class="form__fieldset">
<%= submit_tag 'send', :class => "btn btn--dark-ghost", :id => "submit" %>
</fieldset>
<%end%>
The form should then post to the second route.
To make the loading progress visible I try to use this:
$("#submit").click(function() {
var file_data = $("#input_file").get(0).files[0]
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$(".js-percent").text(String(percentComplete*100) + "%")
}
}, false);
return xhr;
},
url: "message_create",
type: "POST",
data: JSON.stringify(file_data),
contentType: "application/json",
dataType: "json"
});
});
When I try to submit the file the text 0% joust jumps to 100% but I see that the browser is still uploading.
I can't make it work because I don't know ajax so please help me fix this loading progress problem and I'd appreciated if you can recommend me some good tutorials for learning Ajax.
Thank you!

How to work with rails render with ajax javascript request

I have action in controller
def login
#message = params[:mess]
#user = 1
render :rend_log_form
end
the view - rend_log_form.js.erb
l = $("#log_form");
console.log(<%= #message %>);
l.html("<%= j(render(partial: 'login/log_form', locals: {user: #user})) %>");
and some javascript code
$.ajax({
type: "POST",
url: "/login",
data: {mess:"eee"},
success:function(data) {
console.log("SUCCESS POST");
console.log(data);
},
error:function(data) {
console.log("ERROR POST:");
console.log(data);
}
});
action and controller works ok if use link_to with remote: true, but with my javascript code I have in browser console:
ERROR POST:
Object
the Object.responseText - the code of rend_log_form.js.erb
How to render the form with javascript?
Thanks to Hary Bomrah, adding dataType:"html" to ajax call in js code has helped.

Why is this ajax request not appending to the show page at the bottom of the form in Rails 4?

I have a Rails 4.1 controller action called "show" that renders a page with a contact form. When the user hits "Send Now" on the contact form, I want a message notification that will be appended to the "#participant_notification" div id.
Now, when I have all the form fields filled out correctly, a new kite detail is created in the database, however a success message is not appended to #participant notification in the show.html.haml page. Neither is an error message. What is going wrong?
show.html.haml with form:
= form_for #kite_detail, as: :kite_detail, url: send_wind_questions_path, html: { method: :post }, remote: true do |f|
%p Send questions about this kite to us
.input-group
%span
%i.fa.fa-user
= f.text_field :full_name, placeholder: "Full Name"
.input-group
%span
%i.fa.fa-envelope-o
= f.text_field :email, placeholder: "Email address"
.input-group
.left
= f.radio_button :message, "I would like more information about this kite."
%div.right I would like more information about this kite.
.left
= f.radio_button :message, "I, or someone I know would be interested in participating in this kite."
%div.right I, or someone I know would be interested in participating in this kite.
.left
= f.radio_button :message, "I would like to collaborate with the designer."
%div.right I would like to collaborate with the designer.
= f.submit "Send Now", class: "kite-form-button", id: "participant-kite-form"
#participant_notification
I also have a controller action send_wind_questions
def send_wind_questions
#kite_detail = Kite.new(kite_detail_params)
if #kite_detail.save
puts "success"
flash[:success] = "Your message has been sent."
else
puts "error"
flash[:error] = "You didn't specify name, email, or some other error occurred."
end
render nothing: true
end
Here is my ajax javascript:
$('form#new_kite_detail').submit(function() {
var valuesToSubmit = $(this).serialize();
console.log(valuesToSubmit);
$.ajax({
type: "POST",
url: "/send_wind_questions",
data: valuesToSubmit,
dataType: "JSON",
success: function(response) {
$('#participant_notification').append('<p>You have successfully submitted your message.</p>');
},
error: function (request, status, error) {
$('#participant_notification').append(request.responseText);
}
});
return false; // prevents normal behaviour
});

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