Search code examples
jqueryajaxlaravellaravel-5ajaxform

Laravel - Jquery Dynamic Drop Down gives error 500 internal server error


I am trying to fetch the records on the second dropbox based on value selected in the first dropbox. My value in the first dropbox are loading, but when I select a random value, I dont get any values in the second value. I checked my console in the browser and I get the error showing (500 internal server error).

However, when this runned on the local host, it is working absolutely fine. This error occurs only When Running On Live Server

I have a master side bar file, that contains this form. and the ajax code is

    $(document).ready(function(){

     $('.dynamic').change(function(){
      if($(this).val() != '')
      {
       var select = $(this).attr("id");
       var value = $(this).val();
       var dependent = $(this).data('dependent');
       var _token = $('input[name="_token"]').val();
       $.ajax({
          url:"{{ route('pagescontroller.fetch') }}",
        method:"POST",
        data:{select:select, value:value, _token:_token, dependent:dependent},
        success:function(result)
        {
         $('#'+dependent).html(result);
        }

       })
      }
     });
)};

my code in the controller:-

public function index(){
  $pc = $this->getPostcodes();
  $cl = $this->carFetch();
  return view('home')->with('postcodes', $pc)->with('carLists', $cl);
 }

public function getPostcodes(){
     $postcodes =  DB::table('postcodes')
              ->get();

            return $postcodes;
}

public function carFetch(){
    $carLists = DB::table('carlists')
            ->groupBy('Make')
            ->get();
            return $carLists;
}


      function fetch(Request $request)
      {
       $select = $request->get('select');
       $value = $request->get('value');
       $dependent = $request->get('dependent');
       $data = DB::table('carLists')
         ->where($select, $value)
         ->groupBy($dependent)
         ->get();
       $output = '<option value="">Select '.ucfirst($dependent).'</option>';
       foreach($data as $row)
       {
        $output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
       }
       echo $output;
      }

And my Routes:-

Route::get('/', 'PagesController@index')
Route::post('sidebar/fetch', 'PagesController@fetch')->name('pagescontroller.fetch');

Not sure how its working on the localhost and not on the live server.

error screenshot:- enter image description here


Solution

  • The 500 error means that you have an error in your controller, put this into your JavaScript code:

    ...
    success:function(result)
    {
        $('#'+dependent).html(result);
    },
    error: function(result) {
        console.log(result);
    }
    ...
    

    So, you can read the error in the console and post an image in comments to correct it.