keep old select value while validation failed in ajax in laravel

2.9k Views Asked by At

In my Laravel project I have an appointment form where patient can choose a doctor after choosing a branch from the dropdown list. I use AJAX for doing the functionality.

Now after any validation failed all the form value restored accept the doctor.

But I want to automatically restored that selected doctor after validation failed.

html form

<select class="form-control appointment_form_searchField"  id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
    <option value="">Select Branch</option>

    @if($_SESSION['branch'] != null)

      @foreach($_SESSION['branch'] as $data)    
        <option value="{{ $data->id }}">{{ $data->name }}</option>
      @endforeach

   @endif                              
</select>

<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;">
    <option value="">Select Doctor</option>
</select>

AJAX

jQuery(".appointment_form_searchField").change(function() {        
    var branch_id = $("#appointment_branch").val();   
    var token = $('input[name=_token]').val();
    if(branch_id.trim() != '')
    {                
        jQuery.ajax({    
          url:"{{ url('/filter_doctor') }}",
          type: 'GET',
          data: {_token :token, branch_id : branch_id},
          success:function(msg){    
            $('#appointment_doctor option').remove();
            trHTML = '';
            trHTML += "<option value=''>Select Doctor</option>";
            msg.forEach(function(item){    
              trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
            });    
                $('#appointment_doctor').append(trHTML);
            }
        });
    }              
});

controller

public function filter_doctor(Request $request)
{
    $branch_id = $request->branch_id;

    $query =  DB::table('service_doctors');
    $query->select('doctor_id','inactive_dates_in_this_month');

    if($branch_id != '0')
        $query->where('branch_id','=', $branch_id);

    $result_time = $query->get();
    $array_doctor_id = $result_time->pluck('doctor_id');
    $doctor = Doctor::whereIn('id', $array_doctor_id)->get();
    return $doctor;
}

Anybody Help please ? Thanks in advance

1

There are 1 best solutions below

0
On

If you are using Laravel 5 then you can do something like this.

In your form add missing details appointment_branch and appointment_doctor like below.

The Request::old() option load previous posted value in from hence you need to first select old value for appointment_branch'. Also temporary storeold appointment_doctorvalue indata-oldid` so the script can identify which was the old value submitted by user and can load this select box when document is ready.

<select class="form-control appointment_form_searchField"  id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
    <option value="">Select Branch</option>

    @if($_SESSION['branch'] != null)

      @foreach($_SESSION['branch'] as $data)    
        <option value="{{ $data->id }}" {{ Request::old()?(Request::old('appointment_branch')==$data->id?'selected="selected"':''):'' }}>{{ $data->name }}</option>
      @endforeach

   @endif                              
</select>

<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;"   data-oldid="{{ Request::old()?Request::old('appointment_doctor'):'' }}">
    <option value="">Select Doctor</option>
</select>

And then write your script like below.

<script>
    jQuery(document).ready(function($){
        if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
            jQuery(".appointment_form_searchField").change();
        }
    });



    jQuery(".appointment_form_searchField").change(function() {        
        var branch_id = $("#appointment_branch").val();   
        var token = $('input[name=_token]').val();

        if(branch_id.trim() != '')
        {                
            jQuery.ajax({    
              url:"{{ url('/filter_doctor') }}",
              type: 'GET',
              data: {_token :token, branch_id : branch_id},
              success:function(msg){    
                $('#appointment_doctor option').remove();
                trHTML = '';
                trHTML += "<option value=''>Select Doctor</option>";
                msg.forEach(function(item){    
                  trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
                });    
                    $('#appointment_doctor').append(trHTML);
                }
                if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
                    jQuery('#appointment_doctor').val(jQuery("#appointment_doctor").data('oldid')); //select the old doctor id here
                }
            });
        }              
    });

</script>