Reputation:
So I'm using the Kaminari gem to implement infinite scroll in my application. The problem I'm having is giving the controller the search params each time in my Ajax call.
def create
@onsearch = true
@lists = current_user.lists.all
@search = params[:search]
@page = params[:page]
puts "Search is #{@search}, page is #{@page}"
@outfits = Oufits.where("description LIKE ?", "%#{params[:search]}%").page(params[:page]).per(20)
respond_to do |format|
format.html
format.csv { send_data @outfits.to_csv }
format.xls
format.js {render :layout => false }
end
end
This is the ajax I call when users scroll to the bottom of the page:
$.ajax({
type: "GET",
url: url,
data : { search : '<%= @search %>'},
dataType: 'script',
beforeSend: function(){
$('.sk-wave').show();
},
complete: function(){
$('.sk-wave').hide();
},
success: function(response){
$('.sk-wave').hide();
},
error: function(jqXHR, textStatus, errorThrown ){
alert("oh no! ajax went wrong.")
$('.sk-wave').hide();
console.log("jqXHR = "+JSON.stringify(jqXHR));
console.log("textStatus = "+JSON.stringify(textStatus));
console.log("errorThrown = "+JSON.stringify(errorThrown));
}
});
}
The partial that I render when I respond with Javascript is working fine and adds the rest of the content to the page perfectly..
$('.pagecontent').append("<%=j render(partial: 'search/outfits',
format: 'html') %>");
<% if @outfits.current_page == @outfits.total_pages %>
$('#view-more').remove();
<% else %>
$('#view-more a').attr('href', '<%= url_for(page:
@outfits.current_page + 1) %>');
<% end %>
But upon inspection, the search param is received as the literal string'<%= @search %>' in my controller. I've google how to pass a erb variable to javascript but it seems far too complicated for what I'm trying to do. How then can I make sure it's passed each time? Thanks for your help
Upvotes: 0
Views: 532
Reputation: 44370
You have a several problem:
'<%= @search %>'
doesnt works as you expected. Assets files in the app/assets
directroy doesnt have an access to your views variable, because it is precompiled on the server while deploying application.
<input type="hidden" id="foo" name="zyx" value="<%= @search %>" />
var value = $('input#foo').val()
To pass a variable to ajax
use a hidden_input
with the value of @search
, and fetch it by jquery
.
"GET"
doesnt have a body, which means your data
key is passed as query string.
Use "POST"
.
Upvotes: 1