Reputation:
I have:
<p id="click">Click here</p>
In contorller:
def index
@all=Person.all
@person=Person.where(id: params[:id])
respond_to do |format|
format.html
format.js
end
end
and:
$('#click').on('click',function(){
$.ajax({
type: "POST",
data: 'id='+id,
url: "/index"
});
}
index.js.erb
$("#show").html("<%= escape_javascript(render(@person))%>");
_persons.html.erb
<h3><%= @person.name %></h3>
index.html.erb
<div id="show">
<%= render @person %>
</div>
routes
get '/index', to: "main#index" put '/index', to: "main#index"
Now when I got to the index action I get
Person not found with id = nil
Before even the page is loaded. Why is the @person instance variable executed directly? I'm not even able to get to the index page. How does rails ajax work? How does it know the @person variable is to be executed via ajax?
Upvotes: 0
Views: 163
Reputation: 43298
It's not an Ajax error. It's a normal Rails error. You're doing:
@person=Person.where(id: params[:id])
But in the the index action there is no params[:id]
, so what you're actually doing is:
@person = Person.where(id: nil)
That's what the error is about.
The main problem is that you're trying to do two things in one action. You should make a separate action for the Ajax call:
def index
@all = Person.all
end
def ajax_call
@person = Person.where(id: params[:id])
respond_to do |format|
format.html
format.js
end
end
$('#click').on('click',function(){
$.ajax({
type: "POST",
data: 'id='+id,
url: "/ajax_call"
});
}
Something like this. You'll need to add a route for the ajax_call
action, but this is the idea.
Upvotes: 2