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.
Related
I have a button that is used to verify a user's zip code. When clicked, the desired functionality would be an alert display saying whether the zip code was verified or not.
<%= button_tag 'Verify zip code', :type => 'button', :id => 'self-install', remote: true %>
The alert file is in my Views and is in zipcodes/success.js.erb and zipcodes/failure/js.erb
This is my controller:
if data.empty?
respond_to do |format|
format.html do
redirect_to page_path(submitted_page)
end
format.js do
render 'zipcodes/failure'
end
end
else
respond_to do |format|
format.html do
redirect_to page_path(submitted_page)
end
format.js do
render 'zipcodes/success'
end
end
end
Here is my ajax request:
$(function(){
$('#self-install').click(function(e){
e.preventDefault();
$.ajax({
url: '/zipcodes/new',
type: 'get',
dataType: 'json',
data: { zip: zipCodes },
success: function(r){
}
});
});
});
When I click the button, my terminal says this:
But nothing is displaying. I am using Ruby on Rails. Any help would be greatly appreciated. Please let me know if there is anything I left out that would be helpful.
If you have a remote: true element, the ajax call in your js is unnecessary, besides your remote element should be a link_to with the respective url instead of button_tag
Resulting in the following code in your view:
<%= link_to 'new zipcode', new_zipcode_path, remote: true %>
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) %>");
In my view (/app/view/media/index.html.erb) , i have an ajax function and a form_tags:
My AJAX function:
<script type="text/javascript" charset="utf-8">
$(document).ready(
function () {
$("#my_ajax").bind("ajax:success",
function (evt, data, status, xhr) {
console.log(data);
}
).bind("ajax:error", function (evt, data, status, xhr) {
console.log("doh!")
});
});
</script>
.
And my form_tags:
<%= form_tag '/delete_media', method: :delete do %>
<%= submit_tag 'Delete', class: 'btn btn-danger', disabled:#media_contents.empty? , :remote => true, :id => "my_ajax" %>
Our goal : when i get response from server after submit, my_ajax function will be run.
How to do it ??? I can not trigger "my_ajax" function ? I always get JSON response from server
EDIT:
My controller :
def delete_media
#medias=Media.where(id: params[:media_contents]).destroy_all
render json: #medias
end
You should not write js handle ajax like that.
Properly way to implement ajax in rails is:
In /app/view/media/index.html.erb:
form_tag ..., remote: true
In media Controller:
def destroy
# do your job
respond_to do |format|
format.js {}
end
end
In /app/view/media/destroy.js.erb:
// your js handle code
More information: http://guides.rubyonrails.org/working_with_javascript_in_rails.html
maybe try something like this:
<script>
$(document).ready(function(){
$("#my_ajax").on('ajax:success', function(e, data, status, xhr){
console.log(data);
}).on('ajax:error',function(e, xhr, status, error){
console.log('doh!')
});
});
</script>
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
});
Well, maybe the title can't explain it well but i have a form with these lines
- f.collection_select(:client, Client.all, :name, :name)%>
- f.text_field :nit
I need to change in the f.text_field the :nit value from my Client table, according to the chosen Client in the f.collection_select.
Any ideas please??
Please try like this sample code for ajax:
in view Ex:
select_tag "client", options_from_collection_for_select(Client.all, "name", "title"), :prompt => "Select a client", :onchange => "update_text_box(this.value)"
text_field:
text_field_tag :nit,"",:id => "nit"
in script file:
function update_text_box(client_id) {
jQuery.ajax({
url: "/update_text_box",
type: "GET",
data: {"client_id" : client_id},
dataType: "text"
success: function(data) {
jQuery("#nit").val(data);
}
});
}
Now ajax request will go when changing the select_tag.then you have to write logic in your action,finally you have to return the value.like
render :text => some_value.
refer this
Assign id selector to your collection_select and using that selector define an on change function in client side which will call an action through ajax and fetch the required values from database