How To Get Data Using Ajax In Laravel

admin_img Posted By Bajarangi soft , Posted On 18-01-2021

Getting data by ajax from the database is a common requirement in web development. this is a very easy and simple method. Here you automatically get state data from the country.

How To Get Data Using Ajax In Laravel

Step: 1 Create a new table and insert some rows of data and make a model.

In this step, we will create first post table and model.
 
 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
public $table = "country";

protected $fillable = [ 'country_name','description' ];

}
?>


Step: 2 Get data for country dropdown list from the model.
app/Http/Controllers/CountryController.php
public function index()
    {
        $countries = Country::get();
        return view('welcome',compact('countries'));
    }

Step: 3 Make a view page.
resources/views/welcome.blade.php

 


<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <!-- Styles -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
    
<div class="container">
  <br>

   
      <div class="form-group">
  <label class="control-label col-sm-offset-2 col-sm-3" for="company">Country:</label>
  
    <select id="country_id" name="country_id" class="form-control">
        <option value="" selected="selected">--Select Country--</option>
        @foreach($countries as $row)
                      <option value="{{ $row->id }}">{{ $row->country_name }}</option>   
                    @endforeach
    </select> 
  </div>

<br>
<div class="form-group">
  <label class="control-label col-sm-offset-2 col-sm-3" for="company">State:</label>
  
    <select class="form-control" name="state_id" id="state_id">
    <option value="" selected="selected">--Select State--</option>
      
    </select> 
  </div>
  </div>
  </div>

    </body>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
       
       <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#country_id').on('change', function() {
                var id = $(this).val();           
                if(id) {
                    $.ajax({
                        url: '{{url('getting')}}'+'/'+id,
                        type: "GET",
                        dataType: "json",
                        success:function(data) {

                            $('select[name="state_id"]').empty();
                            $.each(data, function(key, value) {
                                $('select[name="state_id"]').append('<option value="'+ key +'">'+ value +'</option>');
                            });
                        }
                    });
                }else{
                    $('select[name="state_id"]').empty();
                }
            });     
        });
    </script>
</html>


Step: 4 Make a route for connection with controller.
app/Http/routes.php
 

Route::get('getting/{id}','CountryController@getting');


Step: 5 Create a function in controller for fetch state data.
app/Http/Controllers/CountryController.php

 


public function getting($id)
    {
        $id = State::where("country_id",$id)
            ->pluck("state_name","id");
        return response()->json($id);
    }


 

Related Post