Search code examples
phpjqueryajaxlaravel

How do I populate a dropdown options from an ajax response


I'm new to ajax. I want to populate a dropdown list from an ajax response. The response is an json of doctors got and I would like to populate a dropdown with this list so the admin can select a particular doctor for a patient.

Here's my ajax code:

$("button").click(function(e) {
    e.preventDefault();
    var id = $(this).val();

    $.ajax({

    type: "POST",
        url: "map/"+id,
        data: { 
            id: $(this).val(),
            '_token': $('input[name=_token]').val() 
        },
        success: function(result) {
            console.log(result);
        },
        error: function(result) {
            alert('error');
        }
    });

Ps: i used console.log so i could view the result

and my laravel controller method:

public function getDoctorSuggests(Request $request){

        $id = $request->id;
        // Get id from database, just skiping this step there
        $patient = Patient::find($id);

        if ($patient instanceof Patient){

            //get patient location details
            $city = $patient->city;

            //get doctors
            $doctors = Doctor::where('city', $city)->get(); //narrow search to city


          if (!$doctors->isEmpty()){
            $distance =[];

            foreach($doctors as $doctor){
            $location = $this->distance($patient->latitude, $patient->longitude, $doctor->latitude, $doctor->longitude, 'K');
            array_push($distance, $location);
            }

            return response()->json(['doctors' => $doctors]);
            }

        return response()->json(['doctors' => NULL]);
        }
    }

Please How do i get the result and populate a html dropdown with it without reloading the page?

the json response is (as gotten from my chrome inspector console)

Object {doctors: Array(2)}doctors: Array(2)0: Objectaddress: "29 Mambilla Street, Abuja, Nigeria"age: 2city: "Abuja"country: "Nigeria"created_at: "2017-06-14 01:01:06"currency: nulldoctor_cv: nulldoctor_mdcn: "wwjdnwe"email: "[email protected]"firstname: "Doctor"id: 1lastname: "Doctor"latitude: 9.0805515longitude: 7.5098858midname: "Midname"phone: "9"place_id: "ChIJ2fEzeToKThARPnGlvU-PKh0"sex: 2state: "FCT"updated_at: "2017-06-14 01:08:52"zip_code: null__proto__: Object1: Objectaddress: "29 Mambilla Street, Abuja, Nigeria"age: 2city: "Abuja"country: "Nigeria"created_at: "2017-06-14 01:01:06"currency: nulldoctor_cv: nulldoctor_mdcn: "wwjdnwe"email: "[email protected]"firstname: "Doctor"id: 3lastname: "Doctor"latitude: 9.0805515longitude: 7.5098858midname: "Midname"phone: "9"place_id: "ChIJ2fEzeToKThARPnGlvU-PKh0"sex: 2state: "FCT"updated_at: "2017-06-14 01:08:52"zip_code: null__proto__: Objectlength: 2__proto__: Array(0)__proto__: Object

Solution

  • First of all try to validate if you doctor model is return something, and then return like this:

    return response()->json($doctors);
    

    The json response will format you output object in an array of objects.

    Now you can populate you combobox like this example bellow.

    $("button").click(function(e) {
    e.preventDefault();
    var id = $(this).val();
    var select = $('#YourSelectBoxID');
    $.ajax({
    
    type: "POST",
        url: "map/"+id,
        data: { 
            id: $(this).val(),
            '_token': $('input[name=_token]').val() 
        },
        success: function(data) {
            var htmlOptions = [];
            if( data.length ){
                  for( item in data ) {
                      html = '<option value="' + data[item].id + '">' + data[item].firstname + '</option>';
                  htmlOptions[htmlOptions.length] = html;
                  }
    
                  // here you will empty the pre-existing data from you selectbox and will append the htmlOption created in the loop result
                  select.empty().append( htmlOptions.join('') );
              }
        },
        error: function(error) {
            alert(error.responseJSON.message);
        }
    })
    

    });

    Good Luck!