Php - Laravel: how to load Ajax data after selected changes from a drop-down list?

I want to load some ajax data after you select a value from the dropdown in the text box.

For example:. After choosing a teacher from the drop-down list, the remaining credits and the credit_taken value should be loaded. How to do it with ajax?

NB: Here the teacher value is selected from another drop-down list selected in Ajax

<script> $('#teacher').on('change',function(e){ var teach_id = $('#teacher option:selected').attr('value'); var info=$.get("{{url('ajax-teach')}}",{teach_id:teach_id}); info.done(function(data){ $.each(data,function(index,subcatObj){ /// Here will be the loaded code /// }); }); info.fail(function(){ alert('ok'); }); }); </script> 

Here is my controller:

 Route::get('ajax-teach',function(Request $request){ $teach_id = $request::input(['teach_id']); $teachers=\App\Teacher::where('teacher_id','=',$teach_id)->get(); return Response::json($teachers); }); 

Here is the view page :

 <div class="form-group"> <label for="">Teacher</label> <select class="form-control input-sm" required name="teacher_id" id="teacher" > <option value=""></option> </select> </div> <div class="form-group"> <label>Credit to be Taken</label> <input type="text" name="credit_taken" id="credit_taken" class="form-control" required placeholder="Credit to be Taken"> </div> <div class="form-group"> <label>Remaining Credit</label> <input type="text" name="remaining_credit" class="form-control" required placeholder="Remaining Credit"> </div> 
+5
source share
1 answer

in the route.php file:

 Route::get( '/ajaxteach', array( 'as' => 'ajaxteach', 'uses' => ' TeachController@get _teach' 

));

your controller: TeachController.php

 class TeachController extends Controller { public function get_teach(Illuminate\Http\Request $request) { $teach_id = $request->get('teach_id'); $teachers=\App\Teacher::where('teacher_id','=',$dept_id)->get(); return response()->json(['response' => '$teachers]); } } 

in ajax script you can use two ways: 1) use an absolute URL in javascript code.

 var base_url = 'http://localhost/laravel' $.ajax({ type: "GET", url : base_url+"/ajaxteach", data : dataString, success : function(data){ console.log(data); } 

2) use url () with the route

  $.ajax({ type: "POST", url : "{{url('ajaxteach')}}", data : dataString, success : function(data){ console.log(data); } 
+7
source

Source: https://habr.com/ru/post/1247910/


All Articles