ajax request not working in rails - ruby-on-rails

I have a controller with this code
def index
if params["destination"].present?
#destination = params["destination"]
#destination_name = params["destination_name"]
#new_loc = (params["current_destination"].present? && (params["destination"] != params["current_destination"]))
......
......
if (#new_loc == false) && params["city_areas"].present?
city_area_ids = params["city_areas"].map(&:to_i)
#hotels = #hotels.select{|ht| city_area_ids.include?( #booking_hotel_partner_details.select{|f| f.partner_booking_hotel_id==ht['id'].to_i}.first.booking_hotel.hotel_city_area_id ) }
end
end
hotels.index.html.haml
$('.checkbox-custom').on('change',function(){
filter_home_stays();
$('#searchForm').trigger('submit.rails');
});
hotels.index.js.erb
if (new_loc == "true") {
$('#city-areas').children('ul.open-dropdown').remove();
$('#city-areas').append('<%= escape_javascript(render :partial => 'filter', :locals => ({:city_areas => #city_areas})) %>');
$('#city_areas .local-amenities-drpdown').mCustomScrollbar({
theme:"rounded-dark",
mouseWheelPixels: 500,
});
}
when click checkbox first time the filter works properly.
But after I change the destination it doesn't work
Can someone help me please?

This is what I did.
if (new_loc == "true") {
$('#city-areas').children('ul.open-dropdown').remove();
$('#city-areas').append('<%= escape_javascript(render :partial => 'filter', :locals => ({:city_areas => #city_areas})) %>');
$('#city_areas .local-amenities-drpdown').mCustomScrollbar({
theme:"rounded-dark",
mouseWheelPixels: 500,
});
$('.city_area.checkbox-custom').on('change',function(){
filter_home_stays();
$('#searchForm').trigger('submit.rails');
});
}
Thanks guys for giving it a shout.You guys rock!

Related

Multiple render in rails controller

Hello I am trying to retrieve html partials as a single string in an ajax call. I am using public_activity gem. Since I didnt find a way to call the partial(render_activity) from the controller. I tried using the following code, but I am getting an error saying that I can not make more than one render call. Any ideas of how can I achieve what I want?
#new_feeds.each_with_index do |new_feed|
if new_feed.trackable_type == "CompanyDocument"
if new_feed.key == "company_document.create"
html = render partial: 'public_activity/company_document/create', :locals => { :activity => new_feed }
elsif new_feed.key == "company_document.update"
html = render partial: 'public_activity/company_document/update', :locals => { :activity => new_feed }
end
elsif new_feed.trackable_type == "CompanyVideo"
if new_feed.key == "company_video.create"
html = render partial: 'public_activity/company_video/create', :locals => { :activity => new_feed }
elsif new_feed.key == "company_video.update"
html = render partial: 'public_activity/company_video/update', :locals => { :activity => new_feed }
end
end
end
Replace all occurrances of render with render_to_string

Rails 3.0 how to create endless page?

I am trying to create a endless page.
After this tutorial: http://railscasts.com/episodes/114-endless-page?view=comments
In my controller I have:
def index
#konkurrencer = Konkurrencer.find(:all).paginate(:page => params[:page], :per_page => 2)
respond_to do |format|
format.html
format.js { render :rjs => #konkurrencer }
end
end
In my view I have:
<% #konkurrencer.each do |kon| %>
<%= render :partial => 'konkurrencers/konkurrencer', :locals => { :kon => kon } %>
<% end %>
My index.js.rjs:
page.insert_html :bottom, :konkurrencer, :partial => 'konkurrencers/konkurrencer'
if #konkurrencer.total_pages > #konkurrencer.current_page
page.call 'checkScroll'
else
page[:loading].hide
end
In my header I this javascript:
<%= javascript_include_tag 'jquery', 'endless' %>
And the endless.js:
var currentPage = 1;
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
new Ajax.Request('/konkurrencer.js?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get'});
} else {
setTimeout("checkScroll()", 250);
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 150;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
document.observe('dom:loaded', checkScroll);
There is no ajax call made or anything. Should move the index.js.rjs to index.js.erb? or is it because I donĀ“t include default javascript?
No, I think the problem your block for responding to js. If you want it to render index.js.rjs, then you just should be able to say:
def index
#konkurrencer = Konkurrencer.find(:all).paginate(:page => params[:page], :per_page => 2)
respond_to do |format|
format.html
format.js
end
end
That should look for a file called index.js.SOMEFORMAT. I dont' believe your :rjs => #koncurrencer is actually working, I bet if you looked at your browser traffic, you'd just see the server return a 500 because of the error.

Rails Javascript if else condition using variable from Controller

View
<%= link_to "Link", {:action => "AjaxView",:col => "colname"},
:update => "Ajaxcall", :remote => true %>
Controller
def AjaxView
#vars= Var.find(:all,:conditions => { :varName=> "one" },:select=>(params[:col]))
respond_to do |format|
format.js { render :layout=>false }
end
end
AjaxView.js.erb
if ( (<%= col %>) == "colName") {
$("#3").text("<%= escape_javascript(render(:partial => "var") %>");
}
else
{
$("#2").text("<%= escape_javascript(render(:partial => "var") %>");
}
Issue here is this Variable "col" doesn't get its exact value in AjaxView.js.erb file, and my If else condition doesn't get executed. What am i missing here ?
The local variable col isn't assigned in AjaxView.js.erb. I think you meant to write it as params[:col].
Also the double quotes around var should be single quotes, to play nice with the surrounding double quotes.
{:action => "AjaxView",:col => "colname"}
This is not how you build a url for link_to.
What's the route to access the AjaxView method?
It should be something like: link_to "Link", AjaxView_resources_path(:col => "colname").
And in your controller, you need to set an instance variable #col = params[:col] to be able to use it in your view.
ps: your should name your method ajax_view instead of AjaxView.
if ( #col.to_s == "colName") {
$("#3").text("<%= escape_javascript(render(:partial => "var") %>");
}
elsif ( #col.to_s == "colName1")
{
$("#2").text("<%= escape_javascript(render(:partial => "var") %>");
}

Implementing a endless scroll with Rails 3 and Jquery

I'm trying to implementing an endless scroll on my project. I'm using a mix of the Railscast #114 Endless Page and this.
Everything works fine besides a weird behavior when I try to stop sending requests when the page hits its end.
So far I have:
Controller:
def show
#title = Photoset.find(params[:id]).name
#photos = Photoset.find(params[:id]).photo.paginate(:page => params[:page], :per_page => 20)
respond_to do |format|
format.js
format.html
end
end
Show.html.erb:
<% content_for :body_class, '' %>
<%= render 'shared/header' %>
<div id="photos_container">
<div id="photos_header">
<h2><%= #title %></h2>
</div>
<%= render :partial => 'photo', :collection => #photos %>
</div>
<%= render :partial => 'endless_scroll' %>
Javascript (loaded via partial):
<script type="text/javascript">
(function() {
var page = 1,
loading = false,
finish = false;
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
function finish() {
finish = true;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage() && !finish) {
loading=true;
page++;
$.ajax({
url: '/photosets/<%= params[:id] %>?page=' + page,
type: 'get',
dataType: 'script',
success: function() {
loading=false;
}
});
}
});
}());
</script>
show.js.erb
$("#photos_container").append("<%= escape_javascript(render :partial => 'photo', :collection => #photos) %>");
<% if #photos.total_pages == params[:page].to_i() %>
page.call 'finish'
<% end %>
As you can see, on my show.js.erb I have a page.call that assigns true to the finish variable. This stops the requests.
The wired thing is that it never loads the last page. When #photos.total_pages == params[:page].to_i() instead of just calling the finish function and setting the variable to true, it's also preventing the $("#photos_container").append("<%= escape_javascript(render :partial => 'photo', :collection => #photos) %>"); from running.
It sends the request to the controller, runs the SQL but doesn't append the last page.
If I change the condition to #photos.total_pages < params[:page].to_i() it works, but send an extra request to a page that doesn't exist.
I'd appreciate any help on my implementation. I'm not sure if there's a more adequate (Rails) way to accomplish this.
First of all you can render html from the partial when request is xhr type:
def show
photoset = Photoset.includes(:photos).find(params[:id])
#title = photoset.name
#photos = photoset.photo.paginate(:page => params[:page], :per_page => 20)
if request.xhr?
render '_photo', :layout => false
end
end
Then use ajax call:
$.ajax({
url: '/photosets/<%= params[:id] %>?page=' + page,
type: 'get',
dataType: 'script',
success: function(response) {
$("#photos_container").append(response);
if (response == "") {
//stop calling endless scroll
}
});
});

Rails keep if false, render if true

I have a div tag that I want to change only if a function returns true, otherwise I want it to keep the same content. I used render: nothing => true but that removes everything.
<%= javascript_include_tag :defaults %>
<div id="x">Hi</div>
<% form_remote_tag :url => {:action => 'get'},
:update => 'x' do %>
<%= text_field_tag 'url' %>
<%= submit_tag "Submit" %>
<% end %>
def getImage
#img = params[:url]
if !verify #img
render :nothing => true
end
end
private
def verify url
return true if url =~ /https?:\/\/.*\.(jpg|png|gif|bmp)$/
return false
end
I want to make my rails code do this
var lastrequest = "";
function ajaxObj() { //Returns the ajax object based on browser
if ( window.XMLHttpRequest ) {
return new XMLHttpRequest(); //Firefox
} else if ( window.ActiveXObject ) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
}
}
window.onload = function() {
document.getElementById("Submit").onclick = function() {
var request = ajaxObj();
request.onreadystatechange = function() {
if ( request.readyState == 4 ) {
document.getElementById("imgdisplay").innerHTML = request.responseText;
document.getElementById("imgurl").value = "";
}
}
if ( lastrequest != document.getElementById("imgurl").value ) { // Makes sure it doesn't request the same image twice
var parameters = "url=" + document.getElementById("imgurl").value;
request.open("POST", "imageget.php", true); // Sends the ajax request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", parameters.length);
request.setRequestHeader("Connection", "close");
request.send(parameters);
lastrequest = document.getElementById("imgurl").value;
}
}
}
use status codes or a failure to control what happens.
http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645
You can also remove the :update => 'x' part an use following code in your controller:
def getImage
#img = params[:url]
if !verify #img
render :nothing => true
else
render :update do |page|
page['x'].replace_html :partial => <some partial here>
end
end
end
Or, a bit briefer:
def getImage
#img = params[:url]
render :update do |page|
page['x'].replace_html(:partial => <some partial here>) if verify(#img)
end
end
Greets

Resources