1

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?

2
  • Is the success method firing? Commented Jun 20, 2015 at 1:21
  • It goes to get_patient.js.erb Commented Jun 20, 2015 at 2:10

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Wait - $('#assessment-type').html('#{j(@patient.name)}'); is literally just rendering #{j(@patient.name)} in my view
NVM: $('#assessment-type').html('<%=j @patient.name %>').html_safe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.