User57
User57

Reputation: 2505

php - Laravel : how to Load Ajax data after selected changes from dropdown?

I want to load some ajax data after selected a value from dropdown in textbox.

Eg: After selecting a teacher from dropdown, teachers remaining credit and credit_taken value should be load. How do I do it with ajax?

NB: Here teacher value has selected from another dropdown selecting 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>

Upvotes: 7

Views: 14991

Answers (1)

Ehsan
Ehsan

Reputation: 459

In your routes (routes/web.php)

Route::get( '/ajaxteach', array(
    'as' => 'ajaxteach',
    'uses' => 'TeachController@get_teach'
) );

In your controller (app/Http/Controllers/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]);
    }
}

Then in your AJAX script you can use at least one of the following ways

  1. use 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 route

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

Upvotes: 9

Related Questions