Example
Step 1 − Create a view file called resources/views/product.php and copy the following code in that file.
<html>
<head>
<title>Laravel Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
<script>
$(document).ready(function () {
$("#pid").change(function (e) {
e.preventDefault();
var $val = $("#pid").val();
var ur = '{{ route("ajx.subproduct",["id" => ":val"]) }}';
var url =ur.replace(':val', $val);
var data = 'pid=' + $val + '&feature=pin';
$.ajax({
url: url,
data: data,
type: 'get',
success: function (output) {
$("#divsubproduct").html(output);
}
})
});
});
</script>
</head>
<body>
Product :
<select name="pid" id="pid" class="form-control">
<option value="">Select Product</option>
@foreach($products as $product)
<option value="{{ $product->pid }}">{{ $product->name }}</option>
@endforeach
</select>
Sub Product :
<div class="col-md-6 col-sm-6" id="divsubproduct">
</div>
</body>
</html>
Step 2 - Create a controller called app/Http/Controllers/ProductController.php
Add This function this controller
/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function Ajaxsubproduct(Request $request, $id) { $pid = $id; $Subproducts = DB::table('sub_products')->where('pid', '=', $pid)->get(); $data ='<select name="sub_pid" id="sub_pid" class="form-control"> <option value="">Select Product</option>'; foreach($Subproducts as $product){ $data.='<option value="'. $product->pid.'">'. $product->name .' </option>'; } $data.='</select>'; return $data; }
Step 3 - Add the following lines in app/Http/routes.php.
Route::get('/associate/ajxsubproducct/{id}', 'ProductController@Ajaxsubproduct')->name('ajx.subproduct');
More explanation how to pass variable into route using javasscript
1) create route and define in url with variable
2) replaced variable of javascript with url variable.
var $val = $("#pid").val();
var ur = '{{ route("ajx.subproduct",["id" => ":val"]) }}';
var url =ur.replace(':val', $val);
No comments:
Post a Comment