Reputation: 5073
I have a dropdown menu of patients. When a user selects a patient from the dropdown menu, I want to use JQUERY to get that patient's ID, then make an AJAX call to the server to return that patient as a variable I can use in my view.
Dropdown:
<%= f.select :patient_id, content_tag(:option,'select
patient...',:value=>"")+content_tag(:option,'New
Patient',:value=>"")+options_from_collection_for_select(@patients, 'id',
'full_name'), :class=>"form-control" %>
JS:
$('#assessment_patient_id').change(function(){
var e = document.getElementById("assessment_patient_id");
var patient_id = (e.options[e.selectedIndex].value)
if (patient_id == 0) {
window.location.href = "/patients/new"
} else {
$.ajax({
type: "POST",
url: "get-patient",
data: {patient_id: patient_id},
success: function(data){
console.log(data)
},
error: function(err){
console.log(err);
}
});
}
Controller:
respond_to :js, :html, :json
def get_patient
@patient = Patient.find(params[:patient_id])
respond_with @patient
end
Routes:
get 'assessments/get-patient', :to => 'assessment#get_patient'
get-patient.js.erb
$('#assessment-type').slideDown(350);
What I'm really trying to accomplish is the ability to go <%= @patient.method_name_here %> in my view after the user selects a patient from the drop down.
But I can't figure out how to get that data back as an object from the controller. Where does it go?
Upvotes: 1
Views: 653
Reputation: 18080
You would do something like this. In the view add a div with the id#patient-name (for example)
Then, the js.erb file can update the dom.
# get-patient.js.erb
$('#assessment-type').slideDown(350);
$('#patient-name').html('#{j(@patient.name)}');
And, could this request go to patients_controller#show instead?
Upvotes: 1