I have this AJAX request:
$("#searchagain_form").submit(function() {
$.ajax({
type: 'POST',
url: "/searchforward",
data: {engine: $("#engine_options").find(".on_engine").text()}
});
});
This is my form:
<%= form_for :searchagain, :url => {:controller => 'results', :action => 'searchforward'}, :html => { :id => "searchagain_form" } do |f| %>
<%= f.text_field :search, :value => #search, :id => 'searchagain_bar' %>
<%= f.submit :value => "search!", :id => 'searchagain_submit' %>
<% end %>
However, checking my logs, the data does not seem to be POSTed to the server when the form is submitted. Any idea why?
You did not cancel the submission, so the page will unload instead of sending the ajax-request.
Append a return false; to the function.
But however, it's not clear what kind of element #engine_options .on_engine is, if it is an text-input use val() instead of text() (text() should return nothing for text-inputs).
When it is a textarea it will return the textNode inside the element, not any later modified text. So use val() also for textarea.
You don't need a semicolon here:
{engine: $("#engine_options").find(".on_engine").text();}
Other than that, you can use a traffic monitor like Charles to monitor the post and make sure it's sending what you want it to.
Edit:
$('#searchagain_form').serialize()
will also give you an object with all your form data
Why don't you add an error handler in your ajax params?
$("#searchagain_form").submit(function() {
$.ajax({
type: 'POST',
url: "/searchforward",
data: {engine: $("#engine_options").find(".on_engine").text()},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
Related
Right now I am displaying notifications for a user on a view. I have the ajax working where it removes the item from the database by clicking the close link. However, what I can't figure out is how to have the view update without actually refreshing the page.
Am I going to have to use a partial of some sort? I haven't really done anything like this and googling is really not helping me since I seem to be going down the rabbit hole.
Right now for my view I have:
<% current_user.notifications.each do |n| %>
<div class="alert alert-info">
<%= link_to 'x', n, :method => :delete, :remote => true, :class => 'delete_notification close' %>
<%= n.title %>
<%= n.description %>
</div>
<% end %>
and then I have my js:
$('.delete_notification').bind('ajax:success', function() {
$(this).closest('tr').fadeOut();
});
I'm not really sure how to ask the question since I am lost on what the 'next step' is. I will provide more information if/when I know what else I need to provide.
Thanks in advance!
UPDATE:
I accepted an answer seeing as it was extremely helpful and exactly what I was looking for!
What I ended up comming up with is:
$(function(){
$(".delete_notification").click(function(){
var $this = $(this);
var url = $this.data('url');
$.ajax(url, {
method: 'DELETE',
type: 'POST',
dataType: 'json',
success: function() {
var parent = $this.parent();
parent.fadeOut("slow");
}
});
});
});
The link_to's callback option (:update) is removed since Rails 3, so I'd rather implement the AJAX link myself.
<% current_user.notifications.each do |n| %>
<div class="alert alert-info">
<%= link_to 'x', n, :class => 'delete_notification close' %>
<%= n.title %>
<%= n.description %>
</div>
<% end %>
Setup AJAX so that it passes Rails' CSRF protection:
$.ajaxSetup({
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}
});
And finally the effect you want:
$('.delete_notification').click(function(ev) {
ev.preventDefault(); // prevent refreshing page
var $this = $(this);
var url = $this.attr('href');
$.ajax(url, {method: 'DELETE'}).done(function() {
$this.closest('tr').fadeOut();
});
});
Maybe you should also modify your controller (I haven't tested this):
class NotificationsController < ApplicationController
# Other actions ...
def destroy
# Your logic (remove rendering or redirection)
head :no_content
end
end
Create a js template in your view called destroy.js.erb, and in that file include the javascript you want to run - something like this:
$('#delete_notification_<%= params[:id] %>').closest('tr').fadeOut();
In your view make sure you specify the ID of the link:
<%= link_to 'x', n, method: :delete, remote: true, class: 'delete_notification close' id: "delete_notification_#{n.object.id}" %>
I have a controller "mainpage", with a correspondingly named view. The controller creates a #myLocalSuites variable, and the view includes the following line:
<li class="active"><%= link_to "Perforce", :action => 'renderp4', :remote => true, :localSuites => #myLocalSuites %></a></li>
Routing is defined such that clicking this link_to calls renderp4.js.erb to render a partial within the mainpage view:
$('#MainPage').replaceWith('<%= escape_javascript render "perforce_sync/perforceSync" %>')
where _perforceSync partial includes:
<%= select_tag "perforceSuites", options_for_select(*MYOPTIONSVARIABLE*), {:class => 'form-control', :size => "20", :multiple => true} %>
Where *MYOPTIONSVARIABLE* needs to be myLocalSuites as cascaded down from the mainpage view/controller.
Having tried everything I can think of, and failed - can someone please show how to modify the above snippets to use the required variable in the PerforceSync partial? Everything I've tried seems to produce something along the lines of:
ActionView::Template::Error (undefined method `map' for nil:NilClass):
An example of what I've tried. I don't think I'm a million miles off, but...
<li class="active"><%= link_to "Perforce", :action => 'renderp4', :remote => true, :localSuites => #myLocalSuites %></a></li>
$('#MainPage').replaceWith('<%= escape_javascript render "perforce_sync/perforceSync", :suitesLocally => params[:localSuites]%>')
<%= select_tag "perforceSuites", options_for_select(params[:suitesLocally]), {:class => 'form-control', :size => "20", :multiple => true} %>
Thanks! :)
In response to your comment, there are two things you can do here. One way is to simply render some dynamic JS on page load, and then use javascript to show that data at a later point.
If this data however is to depend on user actions after the page has loaded, you must make another request to the server using AJAX.
The first way might look like this:
<script>
var my_data = "<%= #some_data %>";
//#some_data could be set by the controller action for example
$('button').click(function() {
$('div.content_container').text(my_data);
});
</script>
The second way would look like this:
<script>
$('button').click(function() {
$.ajax({
url: '/some_resource/id.json',
data: {param1: 'some_user_data'}
}).done(function(data) {
$('div.content_container').text(data);
});
});
</script>
The data option for the ajax call allows you to pass parameters back to the server, so you can send some data provided by the client. Documentation for jquery ajax is here if you want to see other options.
The .done callback gets fired when the client receives a response from the server, and the function parameter is the data returned.
I'm refactoring a form into an AJAX post request.
Here's the existing form:
<%= form_for([#group, #invitation], :remote => true, :html => { :'data-type' => 'html', :class => 'fbinvite_form', :id => friend[:identifier]}) do |f| %>
<%= f.hidden_field :recipient_email, :value => "facebook#meetcody.com" %>
<div class = "fbinvite btn_list_right" id = "<%= friend[:identifier] %>">
<%= f.submit "Invite", :class => "btn btn-medium btn-primary", :name => "fb" %>
</div>
<% end %>
In the controller I have logic that checks for the name of the submit input:
if params[:fb]
...
elsif params[:somethingelse]
...
end
That's the background. I am now trying to replace the above form with the following ajax (added dummy data to make it clearer):
$.post('/groups/7/invitations', {
"recipient_email": "facebook#meetcody.com",
"commit" : "fb",
"fb" : "fb"
}, function(response) {
alert("invite created!");
});
This successfully hits the controller, but doesn't evaluate as true on the condition if params[:fb]. As you can see I tried some really basic ways of passing that parameter in, but it obviously didn't work.
How can I change my ajax request so that params[:fb] evaluates as true?
I want to pass collection_select drop down list value with link_to_remote.
<%= collection_select("event", "trainer_id", #trainers , :id, :name, {:prompt => true}) %>
<%= link_to_remote 'Show calendar', :url => {:controller => 'calendar', :action => 'trainer_view'} %>
I want to pass the selected trainer_id value to the trainer_view method. How can I do this?
Hi :) I would recommend using jQuery and AJAX to accomplish your goal, this is how I would try to do it:
First, I would drop the <%= link_to_remote %> under the collection_select so it would look like this:
<%= collection_select("event", "trainer_id", #trainers , :id, :name, {:prompt => 'Select a Trainer'}) %>
<div id="trainerCalendar"></div>
Then, put this JavaScript in your application.js, when the DOM is ready:
$('#trainer_id').live('change', function() {
$('#trainerCalendar').html.empty;
$.ajax({ url: '/trainer_view/',
data: 'id=' + this.value,
success: function(data) {
$('#trainerCalendar').html(data);
}
})
});
You can have your controller respond with a partial of the calendar.
Hope this helps!
I'm using
<%= text_field 'person', 'one',:id => 'test', :onchange=>remote_function(:url=>{:action=>"update"}, :update=>"test") %>
<div id="test"></div>
Now I just want to send the value of text_field with :action
i.e :url=>{:action=>"update(value_of_text_field_entered"}
Don't want to use params[:person][:one].
Any suggestions?or how can I use <%= observe_field %> to send the value with action?
You can try this one also:
<%= text_field 'person', 'one' %>
### Paste following code in your javascript
$("#person_one").live("change", function(){
$.ajax({
complete:function(request){},
data:'person_one='+ $(this).val(),
dataType:'script',
type:'get',
url: '/update'route
})
});
maybe you can use a javascript code, "this.value()"
Use
<%= text_field 'person', 'one',:id => 'test' %>
<%= observe_field 'persone_one',
:url=>{:action=>"update"} ,
:frequency => 0.25,
:update=>'test',
:with => 'person_one'
%>
<div id="test"></div>
you get value of textfiled in params[:person_one]